Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active September 15, 2019 04:16
Show Gist options
  • Select an option

  • Save stemar/d0d306051ac6c31395a61b9fb0bc181a to your computer and use it in GitHub Desktop.

Select an option

Save stemar/d0d306051ac6c31395a61b9fb0bc181a to your computer and use it in GitHub Desktop.
Format a datetime with a long format
<?php
function long_datetime($datetime, $level = 7) {
$now = new DateTime;
$datetime = new DateTime($datetime);
$suffix = $now > $datetime ? ' ago' : ' ahead';
$diff = $now->diff($dt);
$diff->w = floor($diff->d / 7);
$diff->d -= $diff->w * 7;
$formats = [
'y' => ' year',
'm' => ' month',
'w' => ' week',
'd' => ' day',
'h' => ' hour',
'i' => ' minute',
's' => ' second',
];
$array = [];
foreach ($formats as $key => $value) {
if ($diff->$key) {
$array[$key] = $diff->$key . $value . ($diff->$key > 1 ? 's' : '');
}
}
$array = array_slice($array, 0, $level);
return $array ? join(', ', $array) . $suffix : 'now';
}
<?php
echo long_datetime('2019-11-01');
// => 1 year, 10 months, 2 weeks, 3 days, 17 hours, 42 minutes, 6 seconds ahead
echo long_datetime('2019-11-01', 3);
// => 1 year, 10 months, 2 weeks ahead
echo long_datetime('2014-11-01');
// => 3 years, 1 month, 1 week, 6 days, 6 hours, 20 minutes, 43 seconds ago
echo long_datetime('2014-11-01', 3);
// => 3 years, 1 month, 1 week ago
echo long_datetime('now + 1 week');
// => 1 week ahead
echo long_datetime('1 year, 4 minutes ago');
// => 1 year, 4 minutes ago
echo long_datetime('@1513405762');
// => 1 day, 23 hours, 59 minutes, 50 seconds ahead
echo long_datetime('@0');
// => 47 years, 11 months, 1 week, 6 days, 6 hours, 29 minutes, 58 seconds ago
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment