In short:
I have a time that is in epoch and I want to make it time since January 1, 1970, 00:00:00 GMT
as java.util.Date
would expect to be given.
This code helps demonstrate my issue:
import java.util.Date;
import java.util.Locale;
import org.junit.Test;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
public class TimeHelp {
private String format = "EEE MMM dd HH:mm:ss yyyy";
public SimpleDateFormat asSimpleDateFormat() {
return new SimpleDateFormat(format, Locale.ENGLISH);
}
public DateTimeFormatter asDateTimeFormatter() {
return DateTimeFormatter.ofPattern(format, Locale.ENGLISH);
}
@Test
public void test() throws Exception {
System.out.println(ZoneId.systemDefault());
String s = "Sun Apr 04 02:00:01 2010";
long t1 = asSimpleDateFormat().parse(s).getTime();
ZonedDateTime zoned = LocalDateTime.parse(s, asDateTimeFormatter())
.atZone(ZoneId.systemDefault());
long t2 = zoned.toEpochSecond() * 1000;
long t3 = Date.from(zoned.toInstant()).getTime();
long t4 = zoned.toInstant().toEpochMilli();
System.out.println("t1 " + t1);
System.out.println("t2 " + t2);
System.out.println("t3 " + t3);
System.out.println("t4 " + t4);
System.out.println("Difference in minutes " + Math.abs(t1 - t2)/1000/60);
}
}
And that outputs:
Australia/Sydney
t1 1270310401000
t2 1270306801000
t3 1270306801000
t4 1270306801000
Difference in minutes 60
Note that t1 is different from all the others, I think because t1 is GMT while the others are all UTC.
If I use the SimpleDateFormat
the value of the long is different to if I use the DateTimeFormatter
to get a ZonedDateTime
after which I call toEpochSecond()
.
For reasons I would like to be given a ZonedDateTime
and I want to convert that to a Date
but it looks like such a thing wont work because the Date
works in GMT not UTC
.
Quoting timeanddate.com:
When local daylight time was about to reach
Sunday, April 4, 2010, 3:00:00 am
clocks were turned backward 1 hour toSunday, April 4, 2010, 2:00:00 am
local standard time instead.
Which means that Sun Apr 04 02:00:01 2010
happened twice that day. So which of those 2 do you get?
With SimpleDateFormat
you get the later one, although that is undocumented.
With ZonedDateTime
you get the earlier one:
For Overlaps, the general strategy is that if the local date-time falls in the middle of an Overlap, then the previous offset will be retained. If there is no previous offset, or the previous offset is invalid, then the earlier offset is used, typically "summer" time.. Two additional methods,
withEarlierOffsetAtOverlap()
andwithLaterOffsetAtOverlap()
, help manage the case of an overlap.