在 Java 内从毫秒转换为 UTC 时间

Converting from Milliseconds to UTC Time in Java

我正在尝试将毫秒时间(自 1970 年 1 月 1 日以来的毫秒数)转换为 Java 中的 UTC 时间。我已经看到很多其他使用 SimpleDateFormat 更改时区的问题,但我不确定如何将时间转换为 SimpleDateFormat,到目前为止我只知道如何将它转换为字符串或日期.

例如,如果我的初始时间值为 1427723278405,我可以使用 String date = new SimpleDateFormat("MMM dd hh:mm:ss z yyyy", Locale.ENGLISH).format(new Date (epoch));Date d = new Date(epoch); 将其设置为美国东部时间 3 月 30 日星期一 09:48:45,但每当我尝试更改它时到 SimpleDateFormat 来做类似 this 的事情我遇到了问题,因为我不确定将 Date 或 String 转换为 DateFormat 并更改时区的方法。

如果有人有办法做到这一点,我将不胜感激,谢谢!

试试下面..

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

    }

}

java.time 选项

您可以使用 Java 8 及更高版本中内置的新 java.time package

您可以创建一个 ZonedDateTime 对应于 UTC 时区中的那个时刻:

ZonedDateTime utc = Instant.ofEpochMilli(1427723278405L).atZone(ZoneOffset.UTC);
System.out.println(utc);

如果您需要不同的格式,您也可以使用 DateTimeFormatter,例如:

System.out.println( DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss").format(utc));

你可以检查这个..

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