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
.