Skip to content

Instantly share code, notes, and snippets.

@puiutucutu
Last active December 31, 2017 08:15
Show Gist options
  • Save puiutucutu/a58eb87523802845285b219f2b00007d to your computer and use it in GitHub Desktop.
Save puiutucutu/a58eb87523802845285b219f2b00007d to your computer and use it in GitHub Desktop.
Date functions in php #datetime
<?php
// procedural
$dateDiff = date_diff(
date_create('now'),
date_create('2020-01-01')
);
$days = $dateDiff->days;
$years = $dateDiff->y;
// oop
$daysElapsed = (new DateTime())->diff(new DateTime($album->releaseDate))->days;
<?php
// add days to a DateTime object from today's date
$DateTime = (new \DateTime())->add(
new DateInterval('P' . $dateDifference->d . 'D')
)->format('Y-m-d');
<?php
// multiple ways to get the previous year
$lastYear = ((new DateTime())->format('Y')) - 1;
$lastYear = (new DateTime())->modify('-1 year')->format('Y');
$lastYear = (new DateTime())->sub(new DateInterval('P1Y'))->format('Y');
$lastYear = date('Y') - 1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment