I'm trying to convert a millisecond time (milliseconds since Jan 1 1970) to a time in UTC in Java. I've seen a lot of other questions that utilize SimpleDateFormat to change the timezone, but I'm not sure how to get the time into a SimpleDateFormat, so far I've only figured out how to get it into a string or a date.
So for instance if my initial time value is 1427723278405, I can get that to Mon Mar 30 09:48:45 EDT using either String date = new SimpleDateFormat("MMM dd hh:mm:ss z yyyy", Locale.ENGLISH).format(new Date (epoch));
or Date d = new Date(epoch);
but whenever I try to change it to a SimpleDateFormat to do something like this I encounter issues because I'm not sure of a way to convert the Date or String to a DateFormat and change the timezone.
If anyone has a way to do this I would greatly appreciate the help, thanks!
You can use the new java.time package built into Java 8 and later.
You can create a ZonedDateTime
corresponding to that instant in time in UTC timezone:
ZonedDateTime utc = Instant.ofEpochMilli(1427723278405L).atZone(ZoneOffset.UTC);
System.out.println(utc);
You can also use a DateTimeFormatter if you need a different format, for example:
System.out.println( DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss").format(utc));