Converting from Milliseconds to UTC Time in Java

后端 未结 3 711
粉色の甜心
粉色の甜心 2021-01-01 20:30

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 chan

相关标签:
3条回答
  • 2021-01-01 21:14

    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)));
    
        }
    
    }
    
    0 讨论(0)
  • 2021-01-01 21:22

    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));
    
    0 讨论(0)
  • 2021-01-01 21:25

    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()));
    
    0 讨论(0)
提交回复
热议问题