[英]How to convert UTC time into local time in Java?
我有時間來自 1352437114052 格式的 gpslocation 服務。 有人可以告訴我如何在 Java 或 Matlab 或 Excel 中將其轉換為本地時間。
從紀元以來的毫秒數創建一個新Date
。 然后使用DateFormat
將其格式化為所需的時區。
Date date = new Date(1352437114052L);
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
format.setTimeZone(TimeZone.getTimeZone("PST"));
System.out.println(format.format(date));
這是一個紀元時間,它代表格林威治標准時間 2012 年 11 月 9 日星期五 04:58:34。 該數值是一個絕對的時間點,與時區無關。
如果您想查看不同時區的那個時間點,請使用GregorianCalendar
:
Calendar c = new GregorianCalendar(TimeZone.getTimeZone("EST"));
c.setTimeInMillis(1352437114052L);
c.get(Calendar.HOUR_OF_DAY); //20:58 the day before
使用 JVM 的時區設置(通常與您計算機的時區相同)的現代 Java 答案:
long time = 1_352_437_114_052L;
ZonedDateTime dateTime = Instant.ofEpochMilli(time).atZone(ZoneId.systemDefault());
System.out.println(dateTime);
在我的電腦上運行我得到
2012-11-09T05:58:34.052+01:00[歐洲/哥本哈根]
要指定時區:
ZonedDateTime dateTime = Instant.ofEpochMilli(time).atZone(ZoneId.of("Asia/Almaty"));
2012-11-09T10:58:34.052+06:00[亞洲/阿拉木圖]
在這里回答修補匠的評論:是的。 我正在使用java.time
,現代 Java 日期和時間 API,它在新舊 Android 設備上都能很好地工作。 它只需要至少 Java 6 。
org.threeten.bp
導入日期和時間類。java.time
日期時間。java.time
。java.time
到 Java 6 和 7 的 backport(ThreeTen for JSR-310)。 @Steve Kuo 幾乎直接回答了這個問題。 下面是機器的本地時間更通用的解決方案,包括夏令時,其中a
是類型的BasicFileAttributes
從在Windows目錄條目報道public FileVisitResult visitFile(Path f, BasicFileAttributes a)
在Files.walkFileTree
:
String modifyDate;
Date date = new Date(a.lastModifiedTime().to(TimeUnit.MILLISECONDS));
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
format.setTimeZone(TimeZone.getDefault());
modifyDate = (format.format(date)).substring(0,10);
long timeStamp = System.currentTimeMillis();
System.out.println(timeStamp+"");
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timeStamp);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a z");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString);
輸出 :
timestamp : 1528860439258
dateformat from sdf : 2018-06-12 08:27:19 PM PDT
由於 new Date(String string) 現在已棄用(這是公認的答案),我們可以使用DateTimeZone.getDefault()
來獲取系統時區
public String getZonedDate(String dateStr) {
DateTime utcDateTime = new DateTime(dateStr).toDateTime(DateTimeZone.UTC);
return utcDateTime
.toDateTime(DateTimeZone.getDefault()).toString("yyyy-MM-dd'T'HH:mm:ss");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.