Last active
September 15, 2019 04:16
-
-
Save stemar/d0d306051ac6c31395a61b9fb0bc181a to your computer and use it in GitHub Desktop.
Format a datetime with a long format
This file contains hidden or 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 | |
| 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'; | |
| } |
This file contains hidden or 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 | |
| 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