[英]Is timestamp an utc time? How to get utc time in java and convert to local time (millis)?
[英]Java: How do you convert a UTC timestamp to local time?
我有一個 UTC 時間戳,我想將它轉換為本地時間而不使用像TimeZone.getTimeZone("PST")
這樣的 API 調用。 你到底應該怎么做? 我一直在使用以下代碼但沒有取得多大成功:
private static final SimpleDateFormat mSegmentStartTimeFormatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Calendar calendar = Calendar.getInstance();
try {
calendar.setTime(mSegmentStartTimeFormatter.parse(startTime));
}
catch (ParseException e) {
e.printStackTrace();
}
return calendar.getTimeInMillis();
示例輸入值: [2012-08-15T22:56:02.038Z]
應該返回相當於[2012-08-15T15:56:02.038Z]
Date
沒有時區,內部以 UTC 格式存儲。 只有在格式化日期時才會應用時區校正。 使用DateFormat
,它默認為其運行的 JVM 的時區。使用setTimeZone
根據需要更改它。
DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = utcFormat.parse("2012-08-15T22:56:02.038Z");
DateFormat pstFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
pstFormat.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println(pstFormat.format(date));
這打印2012-08-15T15:56:02.038
請注意,我在 PST 格式中省略了'Z'
,因為它表示 UTC。 如果你只是和Z
一起去,那么輸出將是2012-08-15T15:56:02.038-0700
使用現代 Java 日期和時間 API,這很簡單:
String inputValue = "2012-08-15T22:56:02.038Z";
Instant timestamp = Instant.parse(inputValue);
ZonedDateTime losAngelesTime = timestamp.atZone(ZoneId.of("America/Los_Angeles"));
System.out.println(losAngelesTime);
這打印
2012-08-15T15:56:02.038-07:00[America/Los_Angeles]
注意事項:
Z
表示 UTC,也稱為祖魯時間。 所以在您的本地時間值中, Z
不應該在那里。 相反,您需要一個返回值,例如2012-08-15T15:56:02.038-07:00
,因為偏移現在是 -7 小時而不是 Z。Instant
對象處理。 僅在您有需要時才轉換為ZonedDateTime
,例如用於演示。問:我可以在我的 Java 版本中使用現代 API 嗎?
如果至少使用 Java 6 ,則可以。
這是一個簡單的修改解決方案
public String convertToCurrentTimeZone(String Date) {
String converted_date = "";
try {
DateFormat utcFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
utcFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = utcFormat.parse(Date);
DateFormat currentTFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
currentTFormat.setTimeZone(TimeZone.getTimeZone(getCurrentTimeZone()));
converted_date = currentTFormat.format(date);
}catch (Exception e){ e.printStackTrace();}
return converted_date;
}
//get the current time zone
public String getCurrentTimeZone(){
TimeZone tz = Calendar.getInstance().getTimeZone();
System.out.println(tz.getDisplayName());
return tz.getID();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.