我想將時間戳轉換(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;
}
任何幫助,將不勝感激。
uj5u.com熱心網友回復:
您不能將時間戳轉換為另一個時區,因為時間戳始終是格林威治標準時間,它們是宇宙中時間線中的給定時刻。
我們人類習慣于地球上的當地時間,因此可以將時間戳格式化為更具人類可讀性,并在這種情況下將其轉換為當地時區。
使用遺留的 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),那么情況會更加復雜。
為此,您可以使用一些技巧(例如決議或修改使用上述方法獲得的字串),或使用具有特定類的新 Java 日期和時間類來處理本地時區中的日期和時間:
Instant timestamp = Instant.ofEpochMilli(inputValue);
ZonedDateTime romeTime = timestamp.atZone(ZoneId.of("Europe/Rome"));
請注意第二個示例如何使用“歐洲/羅馬”而不是一般的“CET”。如果您打算處理使用 DST 的時區,這一點非常重要,因為即使它們處于同一時區,DST 更改日(或者是否使用 DST)也可能會因國家/地區而異。
uj5u.com熱心網友回復:
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
細節
您使用的是幾年前由現代所取代可怕舊日期-時間類java.time在JSR 310切勿使用定義的類Timestamp,Calendar,Date,SimpleDateFormat,等。
使用Instant該類表示以 UTC 顯示的時刻,偏移量為零時-分-秒。
long millisecondsSinceBeginningOf1970InUtc = 1_640_812_878_000L ;
Instant instant = Instant.ofEpochMilli( millisecondsSinceBeginningOf1970InUtc ) ;
指定您感興趣的時區。
ZoneID z = ZoneId.of( "Africa/Tunis" ) ;
從零偏移調整到該時區以生成ZonedDateTime物件。
ZonedDateTime zdt = instant.atZone( z ) ;
通過自動本地化生成代表那個時刻的文本。使用 aLocale指定在翻譯中使用的人類語言以及在決定縮寫、大小寫、元素順序等時使用的文化。
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 上多次解決。搜索以了解更多資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/399211.html
