kpb*_*756 11 java datetime date simpledateformat
我正在尝试将毫秒时间(自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);但是每当我尝试将其更改为SimpleDateFormat以执行此类操作时遇到问题因为我是不确定将Date或String转换为DateFormat并更改时区的方法.
如果有人有办法做到这一点,我将非常感谢帮助,谢谢!
ass*_*ias 23
您可以使用Java 8及更高版本中内置的新java.time包.
您可以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));
Pav*_*r K 13
请尝试以下..
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)));
    }
}