簡體   English   中英

如何在Java中使用默認的GMT小時創建日歷

[英]How to create a calendar with the default GMT hours in java

我要從服務器解析很長時間,必須將其解析為一個日期。 我正在使用日歷。

事情是從服務器轉換過來的(它具有用戶本地時間),但是我將其作為默認的GMT並將其也轉換為本地時間。

因此,它轉換了兩次。 既然我做對了,如何在不將其更改為本地的情況下顯示它(默認情況下似乎要這樣做)? 我的代碼:

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));           
calendar.setTimeInMillis(dateLong);
SimpleDateFormat format1 = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
format1.format(cal.getTime());

代替使用Calendar使用SimpleDateFormat 以下代碼向我顯示了正確的結果。

    SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    df.setTimeZone(TimeZone.getTimeZone("GMT"));
    String result = df.format(dateLong);
    System.out.println(result);

其他答案已經提供了CalendarSimpleDateFormat解決方案。 我只想添加另一種方法。

舊的類( DateCalendarSimpleDateFormat )存在很多問題設計問題 ,並且已被新的API取代。

在Android中(如果可以將依賴項添加到項目中-在這種情況下,這是完全值得的,IMO),則可以使用ThreeTen Backport ,它是Java 8的新日期/時間類的絕佳反向端口 為了使其工作,您還需要ThreeTenABP (更多有關如何在此處使用它的信息 )。

首先,您可以使用org.threeten.bp.Instantorg.threeten.bp.Instant值轉換為相應的UTC時刻。 然后,使用org.threeten.bp.format.DateTimeFormatter定義所需日期的格式。 我還使用org.threeten.bp.ZoneOffset來指示格式化程序應使用UTC中的日期:

long dateLong = System.currentTimeMillis();
// convert long millis value to Instant
Instant instant = Instant.ofEpochMilli(dateLong);
// create formatter in UTC
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss")
    .withZone(ZoneOffset.UTC);
// format it
System.out.println(fmt.format(instant));

輸出將類似於:

13/09/2017 11:28:02

抱歉,我誤會了您的時間,以毫秒為單位。 好吧,從那里:

Date dateCreated = new Date(timeInMilliseconds);

然后,當您創建日歷時,只需在設置時間之后設置時區,因為在創建實例時setTimeInMillis會覆蓋您之前的TimeZone設置

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(new java.util.Date().getTime());
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));

而已

暫無
暫無

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

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