php: date difference in days

by prettyscripts on 2010-02-19 11:19:00

php

there are a few ways to calculate how many days between 2 given dates.

the following examples calculates how many days to x'mas from today (19/2/10).

method 1

usingĀ gregoriantojd($month, $day, $year) function to find out the julian day count. without going into the detail what are julian calendar and gregorian calendar, we just wanted the day count to calculate the difference.

PHP:

gregoriantojd(12252010) - gregoriantojd(2192010);

method 2

using strtotime() function to find out the unix timestamp in seconds of the date and calcuate the difference in seconds and convert it to days.

PHP:

strtotime('2010-12-25') - strtotime('2010-2-19') / 
60 60 24// seconds in a day

note date format passed to strtotime() function. since there are different formats used throughout the world, use 'yyyy-mm-dd' just to be safe.

which is better?

personally i like method 1. i don't have to worry about the date format since it takes date parts as parameter and the function returns in days.

Tags: date, day, php

2 comments

Comment by Nico @ 2011-08-03 21:25:02
****-
I like method 1, however in your example you have days and months switched arround. Found it while debuggin it. The correct order is:

int gregoriantojd ( int $month , int $day , int $year )
Comment by Hesh @ 2011-10-03 13:09:13
*****
for ex 1:

you need to type force the dates

((int)strtotime($dates[1]) - (int)strtotime($dates[0])) / ( 60 * 60 * 24)

Leave a comment


Your email address will not be revealed on this site.
PoorExcellent
note: all comments are moderated. do not spam and do not advertise. only comments relevant to the post will be published.
(Line breaks become <br />)
(For my next comment on this site)
(Allow users to contact me through a message form -- Your email will not be revealed!)