我正在尝试使用新的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)
...
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy MM dd");
String text = date.toString(formatter);
LocalDate date = LocalDate.parse(text, formatter);
我认为这可能会有所帮助,您可能需要使用某种本地变量而不是即时变量
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");
|
|
坚强的咖啡豆 · 如何使我的旋转木马自动滑行-腾讯云开发者社区-腾讯云 1 年前 |