Converting from Milliseconds to UTC Time in Java

2020-06-09 13:21发布

问题:

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!

回答1:

Try below..

package com.example;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

public class TestClient {

    /**
     * @param args
     */
    public static void main(String[] args) {
        long time = 1427723278405L;
        SimpleDateFormat sdf = new SimpleDateFormat();
        sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
        System.out.println(sdf.format(new Date(time)));

    }

}


回答2:

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));


回答3:

You May check this..

Calendar calendar = new GregorianCalendar();
    calendar.setTimeInMillis(1427723278405L);

    DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");

    formatter.setCalendar(calendar);

    System.out.println(formatter.format(calendar.getTime()));

    formatter.setTimeZone(TimeZone.getTimeZone("America/New_York"));

    System.out.println(formatter.format(calendar.getTime()));