Date Objects

| | Comments (0)

A colleague just came across an interesting aspect of working with Date objects in Java and JavaScript. In our code we instantiate a new Date object (defaults to today's date) and then conditionally set a specific year, month and day further on in the code. Not very interesting right? But hold on because the order you actually call the setYear/setMonth/setDay methods impacts the final result. For instance, take today, May 31 2002, and let's say the day you want to set it to is June 15 2003. Setting the year to 2003 works as expected. Setting the month to June causes some problems though. At the intermediate stage, before the day has been set, you are holding a Date object set to June 31, 2003. Java and JavaScript will automatically convert this to July 1, 2003. Then you finish setting the day and wonder why the displayed date is July 15, 2003.

On first thought it seems the quick fix is to just set them in the reverse order. But try going from June 15 2003 back to May 31 2002 and you'll see that you'll still have similar problems. In the end, the solution is to first set the day to 1, then set the day/month/year in whichever order suits you best. No rollovers or conversions will occur.

Leave a comment

About this Entry

This page contains a single entry by Dylan published on May 31, 2002 11:41 AM.

Bee Swarm was the previous entry in this blog.

Eclipse is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.