-
Notifications
You must be signed in to change notification settings - Fork 34
Playing the Dating Game
The DateTime object has some advantages over the Java java.util.Date or java.util.Calendar packages. The getDateOnly() method is useful for retrieving day, month and year in single call. But in other areas, it isn't quite so flexible. One of those is comparisons.
There are two methods available - getTimeDifference() and getTimeDifferenceDouble(). I remember the first time I had use of the latter, when my code errored because the dates were too far apart. I'd say getTimeDifference() is there for backwards compatibility, when using a Double might make a noticeable difference in performance.
But I always forget whether the number returned means the DateTime the method is called on is before or after the parameter passed in. And I've never wanted to retrieve the actual time difference and parse it.
So when I saw a tweet from Fiona Sheridan about using Java in SSJS to check if a date was before or after, I knew the code she was talking about, because I've used it in Java myself. Because java.util.Date has an isBefore(DateTime) method and an isAfter(DateTime). Because we were already creating an implementation of DateTime, why not add those methods? So I did. And for completeness equals(DateTime) is implemented. But how about if you want to check two DateTimes are the same date? Or the same time? Using the underlying Java Calendar object, we equalise the relevant portions and compare again, providing methods equalsIgnoreDate(DateTime) and equalsIgnoreTime(DateTime).
I hope you find them useful. I know I will.