Click to See Complete Forum and Search --> : Adding / Subratcing Dates in PHP


webDevShane
09-05-2008, 08:45 AM
Hey how can I accurately add and subtract dates and times in PHP?

I am trying to do something like (2008-09-05 05:32:01) - (2008-09-06 06:23:42) and get a negative number, or better yet, the amount of times in days / hours different that the two dates are.

Any suggestions?

Thanks

-WebDevShane

webDevShane
09-05-2008, 11:33 AM
Anyone please?

NogDog
09-05-2008, 12:12 PM
One approach is to use strtotime() to convert the date strings to UNIX timestamp values, which are an integer number of seconds. Get the difference, which will be in seconds, then convert that to the desired units by dividing by the number of seconds in that unit. (You can use floor() and the % modulus operator to break it up into days/hours/minutes.) The one drawback of this is it can be off by an hour (and possibly a day, depending on how you are doing it) if the time interval crosses a daylight savings time change.

Another approach, albeit less efficient, is one using strtotime() to do "date arithmetic", looping through the addition of days then hours then minutes from one date to the other, as illustrated here: http://www.charles-reace.com/PHP_and_MySQL/Time_Difference/.

Lastly, if the PEAR Date package (http://pear.php.net/package/Date) is available or you can install it, it contains all sorts of useful functions, including a number of "date arithmetic" methods.

webDevShane
09-05-2008, 12:22 PM
Thanks a lot NogDog.