是否有 unix 纪元毫秒的 DateTimeFormatter?
Is there a DateTimeFormatter for unix epoch milliseconds?
是否可以构造一个 java.time.DateFormatter
使得以下等价?
Instant instant = Instant.ofEpochMilli(System.currentTimeMillis());
assert instant.equals(Instant.now);
String str = String.valueOf(instant.toEpochMilli());
Instant instant = Instant.from(formatter.parse(String.valueOf(System.currentTimeMillis())));
assert instant.equals(Instant.now);
String str = formatter.format(instant);
当您的文本输入使用纪元毫秒时,必须进行特殊处理似乎很遗憾。
如果您知道您的日期相当近(自纪元以来的秒数大于 1),您可以使用此格式化程序:
new DateTimeFormatterBuilder()
.appendValue(ChronoField.INSTANT_SECONDS, 1, 19, SignStyle.NEVER)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.toFormatter();
否则,它会有点棘手,您最好直接解析 long 值:
Instant instant = Instant.ofEpochMilli(Long.parseLong(millisString))
System.out.println(instant.toEpochMilli());
是否可以构造一个 java.time.DateFormatter
使得以下等价?
Instant instant = Instant.ofEpochMilli(System.currentTimeMillis());
assert instant.equals(Instant.now);
String str = String.valueOf(instant.toEpochMilli());
Instant instant = Instant.from(formatter.parse(String.valueOf(System.currentTimeMillis())));
assert instant.equals(Instant.now);
String str = formatter.format(instant);
当您的文本输入使用纪元毫秒时,必须进行特殊处理似乎很遗憾。
如果您知道您的日期相当近(自纪元以来的秒数大于 1),您可以使用此格式化程序:
new DateTimeFormatterBuilder()
.appendValue(ChronoField.INSTANT_SECONDS, 1, 19, SignStyle.NEVER)
.appendValue(ChronoField.MILLI_OF_SECOND, 3)
.toFormatter();
否则,它会有点棘手,您最好直接解析 long 值:
Instant instant = Instant.ofEpochMilli(Long.parseLong(millisString))
System.out.println(instant.toEpochMilli());