Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- //By Dominic Gannaway
- /**
- * Check they're set and valid strings
- * @param string $time1
- * @param string $time2
- *
- * @return boolean
- */
- function validateTimestamps($time1, $time2) {
- return isset($time1) && is_string($time1) && isset($time2) && is_string($time2);
- }
- /**
- * PHP 5.2 method - plus it's using math
- * @param string $time1
- * @param string $time2
- *
- * @return int
- */
- function getTimeBetween($time1, $time2) {
- //check the times are valid
- if(validateTimestamps($time1, $time2)) {
- //convert to PHP timestamp
- $time1 = strtotime($time1);
- $time2 = strtotime($time2);
- } else {
- return 'You need to enter some timestamps';
- }
- //find the difference of the two times, taking into consideration the absolute value
- $diff = abs($time1 - $time2);
- //now we need to calculate the minutes, rounding down
- $diff_minutes = floor($diff / 60);
- //return minutes
- return $diff_minutes;
- }
- /**
- * PHP 5.3 method - using the standard DateTime component
- * @param string $time1
- * @param string $time2
- *
- * @return int
- */
- function getTimeBetween2($time1, $time2) {
- //check the times are valid
- if(validateTimestamps($time1, $time2)) {
- $start = new DateTime($time1);
- $end = new DateTime($time2);
- } else {
- return 'You need to enter some timestamps';
- }
- $diff = $start->diff($end);
- //now we have the diff in segments, we need to put them back together
- $diff_minutes = (($diff->days * 24 * 60) + ($diff->h * 60) + $diff->i);
- //return minutes
- return $diff_minutes;
- }
- //should be 60 minutes
- echo getTimeBetween('Thu, 21 Dec 2000 16:01:07 +0200', 'Thu, 21 Dec 2000 17:01:07 +0200') . ' minutes<br>';
- echo getTimeBetween2('Thu, 21 Dec 2000 16:01:07 +0200', 'Thu, 21 Dec 2000 17:01:07 +0200') . ' minutes<br>';
- //should be 120 minutes
- echo getTimeBetween('Thu, 21 Dec 2000 16:01:07 +0200', 'Thu, 21 Dec 2000 19:01:07 +0300') . ' minutes<br>';
- echo getTimeBetween2('Thu, 21 Dec 2000 16:01:07 +0200', 'Thu, 21 Dec 2000 19:01:07 +0300') . ' minutes<br>';
- //should be 6310860 minutes
- echo getTimeBetween('Thu, 7 Dec 2000 16:01:07 +0200', 'Thu, 6 Dec 2012 19:01:07 -0800') . ' minutes<br>';
- echo getTimeBetween2('Thu, 7 Dec 2000 16:01:07 +0200', 'Thu, 6 Dec 2012 19:01:07 -0800') . ' minutes<br>';
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement