java.util.Date has come up a couple times this semester, and I thought I would verify the behavior of Date for dates at and before 1970-01-01. Here's my simple test code:
//Time-stamp: <2014-02-17 11:14:34 jdm>
import java.util.Date;
public class TimeZero {
public static void main(String[] args) {
final int yearsAgo = Integer.parseInt(args[0]);
final double msAgo = yearsAgo
* 365.25 // days per year
* 24 // hours per day
* 60 // minutes per hour
* 60 // seconds per minute
* 1000; // ms per second
final Date d = new Date((long) -msAgo);
System.out.println(d);
} // main()
} // class TimeZero
I'm neglecting leap seconds in my calculation of ms before 1970-01-01 (called msAgo). Assuming that a year averages 365.25 days is also not quite right, but since 2000 was one of those leap years divisible by 400, it's pretty close for recent years. Providing zero as input acts as expected (once one takes the time zone difference between here and Greenwich into account):
> java TimeZero 0
Wed Dec 31 19:00:00 EST 1969
Three years earlier seems to be about right, given that 1968 was a leap year:
> java TimeZero 3
Sun Jan 01 01:00:00 EST 1967
1000 years before 1970 looks good:
> java TimeZero 1000
Sat Dec 18 19:00:00 EST 969
Let's look around near the beginning of CE and the end of BCE (boundary conditions):
> java TimeZero 1967
Tue Dec 19 01:00:00 EST 2
> java TimeZero 1968
Sun Dec 18 19:00:00 EST 1
> java TimeZero 1969
Sat Dec 18 13:00:00 EST 1
This seems odd, but the Gregorian calendar does not have a year zero (see https://en.wikipedia.org/wiki/Gregorian_calendar) and Date.toString() does not include CE/BCE indication. I played around with calendars in my locale to get the era, but cal.get(Calendar.ERA) returns an int, which makes no sense whatsoever, and the problem isn't interesting enough to spend more time on.
However, I am willing to say the Java Date and Calendar hierarchies are entirely too complicated for day-to-day uses. This is one of the few places where I endorse using non-standard class libraries.
No comments:
Post a Comment