JavaScript provides a class “Date” to work with dates. In this short article I want to give some tips with date calculation.
1. Working with seconds
The easiest way, if you need to calculate with seconds, minutes or hours, is to use the provided methods getTime() or setTime(). Here you will get or you can set the microseconds since 1.1.1970. So if you want to add one hour, just add 3.600.000 microseconds:
1 2 | var date = new Date(); date.setTime(date.getTime()+3600000); |
2. Working with days
If you work with days, the way with getTime()/setTime() is not preferred, because you have to honour the summer / winter time. So calculating with days, months or years should be done using the provided methods getDate() / setDate(), getMonth() / setMonth() or getFullYear() / setFullYear(). These methods are fault tolerant, so you can set the 35. day of a month and the date is correctly converted to the given day in the next month.
1 2 | var date = new Date(2009,1,25); //date is 2009-02-25 date.setDate(date.getDate()+5); //would change date to 2009-03-02 |