Skip to content

Instantly share code, notes, and snippets.

@ryanmerritt
Forked from ziadoz/datetime.php
Created September 18, 2012 10:18
Show Gist options
  • Save ryanmerritt/3742438 to your computer and use it in GitHub Desktop.
Save ryanmerritt/3742438 to your computer and use it in GitHub Desktop.
Using PHP DateTime
<?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