我正在尝试使用新的java 8 time-api和模式将Instant格式化为字符串:
Instant instant = ...;
String out = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(instant);
使用上面的代码,我得到了一个异常,它报告一个不支持的字段:
java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: YearOfEra
at java.time.Instant.getLong(Instant.java:608)
at java.time.format.DateTimePrintContext.getValue(DateTimePrintContext.java:298)
...
发布于 2018-02-03 18:50:12
public static void main(String[] args) {
DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault());
System.out.println(DATE_TIME_FORMATTER.format(new Date().toInstant()));
}
发布于 2019-03-08 06:58:25
DateTimeFormatter.ISO_INSTANT.format(Instant.now())
这使您不必转换为UTC。但是,其他一些语言的时间框架可能不支持毫秒,所以您应该这样做
DateTimeFormatter.ISO_INSTANT.format(Instant.now().truncatedTo(ChronoUnit.SECONDS))
发布于 2014-12-13 00:27:38
Instant
类不包含区域信息,它只存储从UNIX纪元开始的毫秒时间戳,即来自UTC的1070年1月1日。因此,格式化程序不能打印日期,因为总是打印特定时区的日期。您应该将时区设置为格式化程序,然后一切都会很好,如下所示:
Instant instant = Instant.ofEpochMilli(92554380000L);
DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.SHORT).withLocale(Locale.UK).withZone(ZoneOffset.UTC);
assert formatter.format(instant).equals("07/12/72 05:33");
assert instant.toString().equals("1972-12-07T05:33:00Z");
https://stackoverflow.com/questions/25229124
复制相似问题