note 94488 modified in function.date-diff by danbrown

From: Date: Sun, 08 Nov 2009 16:19:07 +0000
Subject: note 94488 modified in function.date-diff by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-162639@lists.php.net to get a copy of this message
[This time-compare function is a combination of multiple notes by the same author.] <?php function timeDiff($ts1, $ts2) { if ($ts1 < $ts2) { $temp = $ts1; $ts1 = $ts2; $ts2 = $temp; } else { $temp = $ts1; } $format = 'Y-m-d H:i:s'; $ts1 = date_parse(date($format, $ts1)); $ts2 = date_parse(date($format, $ts2)); $arrBits = explode('|', 'year|month|day|hour|minute|second'); $arrTimes = array(0, 12, date("t", $temp), 24, 60, 60); foreach ($arrBits as $key => $bit) { $diff[$bit] = $ts1[$bit] - $ts2[$bit]; if ($diff[$bit] < 0) { $diff[$arrBits[$key - 1]]--; $diff[$bit] = $arrTimes[$key] - $ts2[$bit] + $ts1[$bit]; } } return $diff; } $born_date = mktime(6, 30, 0, 7, 24, 2008); $date_diff_array = timeDiff($born_date, time()); print_r($date_diff_array); ?> You can also leave out the "else" part of the first if-statement, and change the line: <?php $arrTimes = array(0, 12, date("t", $temp), 24, 60, 60); ?> to <?php $arrTimes = array(0, 12, date("t", $ts1), 24, 60, 60); ?> as $temp will always be $ts1 >> Special thanx to Tobias for sending me the tip << --was-- Sorry! Forgot a line of code. Here's the correct version: <?php function timeDiff($ts1, $ts2) { if ($ts1 < $ts2) { $temp = $ts1; $ts1 = $ts2; $ts2 = $temp; } else { $temp = $ts1; } $format = 'Y-m-d H:i:s'; $ts1 = date_parse(date($format, $ts1)); $ts2 = date_parse(date($format, $ts2)); $arrBits = explode('|', 'year|month|day|hour|minute|second'); $arrTimes = array(0, 12, date("t", $temp), 24, 60, 60); foreach ($arrBits as $key => $bit) { $diff[$bit] = $ts1[$bit] - $ts2[$bit]; if ($diff[$bit] < 0) { $diff[$arrBits[$key - 1]]--; $diff[$bit] = $arrTimes[$key] - $ts2[$bit] + $ts1[$bit]; } } return $diff; } $born_date = mktime(6, 30, 0, 7, 24, 2008); $date_diff_array = timeDiff($born_date, time()); print_r($date_diff_array); ?> http://php.net/manual/en/function.date-diff.php

« previous php.notes (#162639) next »