I want to let users easily add and subtract dates using JavaScript in order to browse their entries by date.
The dates are in the format: "mm/dd/yyyy". I want them to be able to click a "Next" button, and if the date is: " 06/01/2012" then on clicking next, it should become: "06/02/2012". If they click the 'prev' button then it should become, "05/31/2012".
It needs to keep track of leap years, number of days in the month, etc.
Any ideas?
P.S using AJAX to get the date from the server isn't an option, its a bit laggy and not the experience for the user that the client wants.
Working with dates in javascript is always a bit of a hassle. I always end up using a library. Moment.js and XDate are both great:
http://momentjs.com/
http://arshaw.com/xdate/
Fiddle:
http://jsfiddle.net/39fWa/
This is the only solution that works reliably when adding/subtracting across months and years. Realized this after spending way too much time mucking around with the getDate and setDate methods, trying to adjust for month/year shifts.
decasteljau (in this thread) has already answered this but just want to emphasize the utility of this method because 90% of the answers out there recommend the getDate and setDate approach.
May be this could help
You need to use
getTime()
andsetTime()
to add or substract the time in a javascript Date object. UsingsetDate()
andgetDate()
will lead to errors when reaching the limits of the months 1, 30, 31, etc..Using setTime allows you to set an offset in milliseconds, and let the Date object figure the rest:
you can try here: http://jsfiddle.net/ZQAHE/
You can use the native javascript Date object to keep track of dates. It will give you the current date, let you keep track of calendar specific stuff and even help you manage different timezones. You can add and substract days/hours/seconds to change the date you are working with or to calculate new dates.
take a look at this object reference to learn more:
Date
Hope that helps!