簡體   English   中英

在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));將其發送到美國東部時間3月30日09:48:45 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並更改時區。

如果有人有辦法做到這一點,我將非常感謝幫助,謝謝!

java.time選項

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

您可以在UTC時區中創建與該時刻對應的ZonedDateTime

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

請嘗試以下..

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

    }

}

你可以檢查這個..

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM