Calendars, Dates, and "yesterday"
I wrote a program to convert the log files from a game into HTML. I got some feedback from a user saying that sometimes the date range it converts is wrong. I can't reproduce it, so it might be an error with the user's scripts. But I just want to make sure this code does what I think it does.
This code is supposed to return a Date corresponding to midnight at the beginning of yesterday in the user's local time zone.
Code:
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.add(Calendar.DATE, -1);
return cal.getTime();
Re: Calendars, Dates, and "yesterday"
You'll get a Date object representing that time in millis from epoch (ie UTC essentially), so it all depends how that is being used. Sounds like the display of it is going wrong somewhere?
Re: Calendars, Dates, and "yesterday"
I take the Dates I get from the above code, parse dates from the log using a SimpleDateFormat, and compare them using before(...) and after(...). The log doesn't specify a time zone, but I think the SimpleDateFormat assumes the system time zone. Maybe I'm wrong.
Code:
private static final SimpleDateFormat format =
new SimpleDateFormat("MM/dd/yy hh:mm:ss a");
Re: Calendars, Dates, and "yesterday"
While using SimpleDateFormat is worth noting that its not thread-safe and should not be used in multi-threading environment.
Re: Calendars, Dates, and "yesterday"
That's just what I was going to point out...it's possible (if you're in a multi-threaded situation) that that could be the cause?
Anyway, you're correct that SDF defaults to system TZ.
Re: Calendars, Dates, and "yesterday"
The app is single-threaded... no explicitly created threads and no GUI.
If my Calendar manipulations produce a Date corresponding to midnight at the beginning of yesterday in the system TZ, and my SimpleDateFormat is also using the system TZ, then I assume it was an external problem. Maybe the user's system clock was off when he converted his logs.
Re: Calendars, Dates, and "yesterday"
I suspect that would have to be the place to look.
As you say, the Calendar is system TZ, as is that SDF, so they should produce the same time.