Reputation: 27326
All,
I am working with a binary specification whose TimeStamp fields are defined as "Milliseconds since January 1, 2000 UTC time". I am doing the following calculation:
public static final TimeZone UTC = TimeZone.getTimeZone("UTC") ;
public static final Calendar Y2K_EPOCH = Calendar.getInstance(UTC);
static {
Y2K_EPOCH.clear();
// Month is 0 based; day is 1 based. Reset time to be first second of January 1, 2000
Y2K_EPOCH.set(2000, 0, 1, 0, 0, 0);
}
public static final long MS_BETWEEN_ORIGINAL_EPOCH_AND_Y2K_EPOCH = Y2K_EPOCH.getTimeInMillis();
public static long getMillisecondsSinceY2K(Date date) {
long time = date.getTime();
if (time < MS_BETWEEN_ORIGINAL_EPOCH_AND_Y2K_EPOCH) {
throw new IllegalArgumentException("Date must occur after January 1, 2000");
}
return time - MS_BETWEEN_ORIGINAL_EPOCH_AND_Y2K_EPOCH;
}
My question is, is this the correct way to do the conversion between standard Java Date objects and this datatype? Is there a better way of doing this? I know about Joda time but I'd rather not bring that external dependency in if I can help it.
Upvotes: 3
Views: 1070
Reputation: 53496
Time is a tricky mess, especially UTC time. Assuming you want a pretty good time based of an arbitrary epoch, a simple subtraction like what you do should be fine. If you are worried about leap-seconds precision I would highly suggest you use Joda or some reliable external library.
Upvotes: 0
Reputation: 420971
Looks good to me.
Note that you could change
long time = date.getTime();
if (time < MS_BETWEEN_ORIGINAL_EPOCH_AND_Y2K_EPOCH)
...
to
if (date.before(Y2K_EPOCH))
...
Regarding your worry about leap seconds, here is an excerpt from the docs:
Although the Date class is intended to reflect coordinated universal time (UTC), it may not do so exactly, depending on the host environment of the Java Virtual Machine. Nearly all modern operating systems assume that 1 day = 24 × 60 × 60 = 86400 seconds in all cases. In UTC, however, about once every year or two there is an extra second, called a "leap second." The leap second is always added as the last second of the day, and always on December 31 or June 30. For example, the last minute of the year 1995 was 61 seconds long, thanks to an added leap second. Most computer clocks are not accurate enough to be able to reflect the leap-second distinction.
Upvotes: 1