PHP: Calculate Difference Between Dates As Strings
Posted by Kieran - 05/06/08 at 08:06:04 amThere are plenty of well documented methods to calculate the difference between two dates. However its not so easy when you don’t have a date type, but a string which represents a date. You could turn the string into a date, then do some math and come up with a difference but thats long winded!
The easiest method when you have a string such as “21/06/08″ is to work out what day of the year that is (between 0 and 365) and subtract one from the other.
This function uses the explode function to seperate the string into parts (you’ll see the first variable is ‘/’ which happens to be my delimiter in this case, you could use ‘-’ or something similar) and gregoriantojd which takes the month, day and year in that order to return the day number in that year.
$day1 = explode('/', $day1);
$day2 = explode('/', $day2);
$start_date=gregoriantojd($day1[1], $day1[0], $day1[2]);
$end_date=gregoriantojd($day2[1], $day2[0], $day2[2]);
$days = $end_date - $start_date;
So American formatted dates would need a switch in the variables of the gregoriantojd function to 0, 1 ,2 or M, D, Y as they usually show their months first.
No Comments yet »
RSS feed for comments on this post. TrackBack URI
Leave a comment
Powered by WordPress with GimpStyle Theme heavily modified by Kieran Delaney.
Entries and comments feeds.
Valid XHTML and CSS. 20,414 spam comments ignored.