簡體   English   中英

將時間戳轉換為特定時區的日期時間

[英]Convert timestamp to Date time for a particular timezone

我想將時間戳(which is in GMT)轉換為local date and time

這是我迄今為止實施的,但它給了我錯誤的月份

Timestamp stp = new Timestamp(1640812878000L);
Calendar convertTimestamp = convertTimeStamp(stp,"America/Phoenix");
System.out.println(convertTimestamp.getTime());
    

public static Calendar convertTimeStamp( Timestamp p_gmtTime, String p_timeZone) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("MMM dd, yyyy HH:MM:SS a", Locale.ENGLISH);
        DateFormat formatter = DateFormat.getDateTimeInstance();
        if (p_timeZone != null) {
            formatter.setTimeZone(TimeZone.getTimeZone(p_timeZone));
        } else {
            formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
        }

        String gmt_time = formatter.format(p_gmtTime);
        Calendar cal = Calendar.getInstance();
        cal.setTime(sdf.parse(gmt_time));
        return cal;
    }

任何幫助,將不勝感激。

您不能將時間戳轉換為另一個時區,因為時間戳始終是 GMT,它們是宇宙中時間線上的給定時刻。

我們人類習慣於地球上的當地時間,因此可以將時間戳格式化為更易於閱讀,並在這種情況下將其轉換為當地時區。

使用舊版 java.util.* 包,按如下方式完成:

DateFormat tzFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
tzFormat.setTimeZone(TimeZone.getTimeZone("CET")); // Use whatever timezone
System.out.println(tzFormat.format(date));

如果您需要對本地時區的時間戳進行“數學運算”(例如,明天本地時區的 8:00),那么情況會更加復雜。

為此,您可以訴諸一些技巧(例如解析或修改通過上述方法獲得的字符串),或使用具有特定 class 的新 Java 日期和時間類來處理本地時區的日期和時間:

Instant timestamp = Instant.ofEpochMilli(inputValue);
ZonedDateTime romeTime = timestamp.atZone(ZoneId.of("Europe/Rome"));

請注意第二個示例如何使用“Europe/Rome”而不是一般的“CET”。 如果您計划處理使用 DST 的時區,這一點非常重要,因為 DST 更改日期(或者是否使用 DST)可能會因國家/地區而異,即使它們位於同一時區。

tl;博士

Instant
.ofEpochMilli(                       // Parse a count of milliseconds since 1970-01-01T00:00Z.
    1_640_812_878_000L
)                                    // Returns a `Instant` object.
.atZone(                             // Adjust from UTC to a time zone. Same moment, same point on the timeline, different wall-clock time.
    ZoneId.of( "America/Phoenix" ) 
)                                    // Returns a `ZonedDateTime` object.
.format(                             // Generat text representing the date-time value kept within that `ZonedDateTime` object.
    DateTimeFormatter
    .ofLocalizedDateTime( FormatStyle.MEDIUM )
    .withLocale( Locale.US ) 
)                                    // Returns a `String` object.

請參閱在 IdeOne.com 上實時運行的代碼

2021 年 12 月 29 日下午 2:21:18

細節

您正在使用多年前被 JSR 310 中定義的現代java.time類取代的糟糕的舊日期時間類。切勿使用TimestampCalendarDateSimpleDateFormat等。

使用Instant class 來表示以 UTC 表示的時刻,偏移量為零時分秒。

long millisecondsSinceBeginningOf1970InUtc = 1_640_812_878_000L ;
Instant instant = Instant.ofEpochMilli( millisecondsSinceBeginningOf1970InUtc ) ;

指定您感興趣的時區。

ZoneID z = ZoneId.of( "Africa/Tunis" ) ;

從零偏移量調整到該時區以生成ZonedDateTime object。

ZonedDateTime zdt = instant.atZone( z ) ;

通過自動本地化生成代表那一刻的文本。 使用Locale來指定在翻譯中使用的人類語言以及在決定縮寫、大小寫、元素順序等時使用的文化。

Locale locale = Locale.JAPAN ; // Or Locale.US, Locale.ITALY, etc.
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime( FormatStyle.LONG ).withLocale( locale ) ;
String output = zdt.format( f ) ;

所有這些都已在 Stack Overflow 上多次解決。 搜索以了解更多信息。

暫無
暫無

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

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