Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting from Milliseconds to UTC Time in Java

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!

like image 594
kpb6756 Avatar asked Jul 08 '15 12:07

kpb6756


People also ask

How do you convert UTC time to milliseconds?

The getUTCMilliseconds() method is used to get the milliseconds from a given date according to universal time (UTC). The value return by getUTCMilliseconds() method is a number between 0 and 999.

How do you convert milliseconds to timestamps?

Use the Date() constructor to convert milliseconds to a date, e.g. const date = new Date(timestamp) . The Date() constructor takes an integer value that represents the number of milliseconds since January 1, 1970, 00:00:00 UTC and returns a Date object.

How do you convert milliseconds to hours in Java?

If TimeUnit or toMinutes are unsupported (such as on Android before API version 9), use the following equations: int seconds = (int) (milliseconds / 1000) % 60 ; int minutes = (int) ((milliseconds / (1000*60)) % 60); int hours = (int) ((milliseconds / (1000*60*60)) % 24); //etc...


1 Answers

java.time option

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));
like image 71
assylias Avatar answered Sep 17 '22 13:09

assylias