-
-
Save ryanmerritt/3742438 to your computer and use it in GitHub Desktop.
Using PHP DateTime
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Comparison and Formatting | |
$start = new DateTime('now'); | |
$end = new DateTime('2014-02-01'); | |
echo 'Start: ' . $start->format('d M Y') . "\n"; | |
echo 'End: ' . $end->format('d M Y') . "\n"; | |
$diff = $end->diff($start); | |
echo 'Comparison: ' . ($start < $end ? 'Start is less than End' : 'End is less than Start') . "\n"; | |
echo 'Interval: ' . $diff->format('%y Year(s), %m Month(s), %d Day(s)') . "\n\n"; | |
// Intervals and Formatting | |
$start = new DateTime('now'); | |
$end = new DateTime('next friday'); | |
$interval = new DateInterval('P1D'); | |
echo 'Start: ' . $start->format('d M Y') . "\n"; | |
echo 'End: ' . $end->format('d M Y') . "\n"; | |
echo 'Days Between: ' . "\n"; | |
$period = new DatePeriod($start, $interval, $end); | |
foreach ($period as $date) { | |
echo $date->format('d M Y') . "\n"; | |
} | |
// Format Time Ago Helper | |
function formatTimeAgo($timestamp) | |
{ | |
$then = new DateTime($timestamp); | |
$now = new DateTime('now'); | |
$interval = $now->diff($then); | |
$bits = array( | |
'year' => $interval->y, | |
'month' => $interval->m, | |
'day' => $interval->d, | |
'hour' => $interval->h, | |
'minute' => $interval->i, | |
'second' => $interval->s, | |
); | |
foreach ($bits as $type => $value) { | |
if ($value > 0) { | |
return $value . ' ' . ($value > 1 ? $type . 's' : $type) . ' ago'; | |
} | |
} | |
return false; | |
} | |
echo 'Format Time Ago: ' . formatTimeAgo('2012-08-12'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment