Skip to content

Java date arithmetic

I am used to using the old (deprecated) WebObjects NSTimestamp class to do basic arithmetic on dates; it was easy with one method call to add an arbitrary number of days/weeks and get the correct date, or even to calculate the difference between two dates. In the new (release 5.0, so not that new) world of WebObjects, these methods are deprecated, although they do still exist. I see that NSTimestamp is a subclass of Date, so that lets us into the world of pure Java. The documentation points you to GregorianCalendar for further edification. A bit of scanning around shows me that Date has an add() method; for differences, use this: double days = (toDate.getTime()-fromDate.getTime())/1000/60/60/24; Seems very crude to me. It will calculate a date interval in days, meaning 24 hour periods rather than midnight transitions. It will also round down, courtesy of the cast to (double), which is necessary to prevent a “loss of precision” compiler error.

Post a Comment

Your email is never published nor shared. Required fields are marked *