I need to store year-moth-day information w/o timezone info.
Here’s some code:
private static void test() {
Calendar cal = Calendar.getInstance();
cal.setTimeZone(TimeZone.getTimeZone("US/Pacific"));
System.out.println("Before: " + cal.get(DAY_OF_MONTH));
//
long datestamp = toDatestamp(cal.getTimeInMillis());
long timestamp = toTimestamp(datestamp);
cal.setTimeInMillis(timestamp);
System.out.println("After: " + cal.get(DAY_OF_MONTH));
}
private static long toTimestamp(long datestamp) {
return TimeUnit.DAYS.toMillis(datestamp);
// return datestamp * DS_MULT;
}
private static long toDatestamp(long timestamp) {
return TimeUnit.MILLISECONDS.toDays(timestamp);
// return timestamp / DS_MULT;
}
// hours * minutes * seconds * milliseconds
private static long DS_MULT = 24 * 60 * 60 * 1000;
with 2 approaches, one of which is commented out. But result is the same:
Before: 26
After: 25
Why does the date change after conversion? Am I missing something obvious?
By converting to days and back to milliseconds, you’re effectively re-setting the calendar to midnight of that day. But, when you set the time in milliseconds, it’s interpreted as UTC time (roughly equivalent to GMT), so you’re resetting the calendar to midnight UTC. Because the timezone “US/Pacific” has a negative offset from UTC, it appears as the previous day.
You can see this by adding another line at the end of test:
And you should see: