contact

Archive for November 9th, 2008

calculating the number of days between two dates

Sunday, November 9th, 2008

for a recent project I had to figure out how many days are between a given start and end date. My first very poor attempt was to split the dates and then get the monthes and then add up the days for each month. Very poor on performance.

The easy solution:

most modern programming languages offer Dates Objects that can handle timestamps, which makes our calculation very easy.

(Timestamp(endDate)-TimeStamp(startDate)) / 3600 / 24 = days

this will compute the amount of seconds between the start and end date, then divide by 3600 gives you get hours, divide by 24 and you have the number of days. This is especially nice since it automatically considers 29th of february.

note: if you use actionscript you have to again divide by 1000 since its timestamps are in milli seconds.

actionscript 3 screenshot

actionscript 3 screenshot