問題描述
使用 java.time.DateTimeFormatter 格式化 java Date,包括時間偏移 (Formating java Date with java.time.DateTimeFormatter including time offset)
我需要怎麼做?我知道我總是可以回退到使用單線程本地 SimpleDateFormat 實例,但我想使用新的 java.time 東西:‑)</p>
參考解法
方法 1:
Date date = new Date();
System.out.println(DateTimeFormatter.ISO_INSTANT.format(date.toInstant()));
// output: 2015‑11‑22T14:46:08.776Z
System.out.println(DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(
date.toInstant().atZone(ZoneId.systemDefault())));
// output: 2015‑11‑22T15:46:08.776+01:00
System.out.println(DateTimeFormatter.ISO_OFFSET_DATE_TIME
.withZone(ZoneId.systemDefault())
.format(date.toInstant()));
// output: 2015‑11‑22T15:46:08.776+01:00
</code></pre>
參考文件