如何自定义格式化FileTime

Mus*_*ful 8 java date-formatting java-time

给定a FileTime fileTime,如何以自定义方式格式化为字符串?

String s = fileTime.toString() 仅以ISO格式提供.

String s = DateTimeFormatter.ofPattern("uuuu-MMM-dd HH:mm:ss")
                              .format(fileTime.toInstant());
Run Code Online (Sandbox Code Playgroud)

UnsupportedTemporalTypeException: Unsupported field: Year

Men*_*ild 6

我个人发现错误消息"不支持的字段:年"误导.真正的原因是缺少时区.需要此信息来帮助格式化程序在内部将给定的瞬间转换为人工时间表示.解决方案:提供时区.然后Instant支持格式化或解析a - 与@flo的答案形成对比.

印刷:

String s = 
  DateTimeFormatter.ofPattern("uuuu-MMM-dd HH:mm:ss", Locale.ENGLISH)
    .withZone(ZoneId.systemDefault())
    .format(Instant.now());
System.out.println(s); // 2015-Oct-30 15:22:32
Run Code Online (Sandbox Code Playgroud)

解析:

不幸的是,反向过程 - 解析 - 不能以相同的直接方式工作,因为格式引擎的java.time设计使得格式化程序只返回TemporalAccessor需要转换为实际所需类型的raw .例:

Instant instant =
  Instant.from(
    DateTimeFormatter.ofPattern("uuuu-MMM-dd HH:mm:ss", Locale.ENGLISH)
    .withZone(ZoneId.systemDefault())
    .parse("2015-Oct-30 15:22:32"));
System.out.println("=>" + instant); // 2015-10-30T14:22:32Z
Run Code Online (Sandbox Code Playgroud)

如果要解析的输入包含时区偏移或标识符,那么您可以修改模式(符号x,X,z,Z,VV等)并省略调用withZone(...),如果有偏移 - 你真的应该离开超出该调用,因为否则格式化程序将不使用输入的时区偏移量,而是使用提供的一个区域(我在自己的测试中观察到的陷阱).


flo*_*flo 4

DateTimeFormatter您无法使用查询年份的实例来格式化 Instant 。

AnInstant代表时间线上的单个点。这就是为什么不可能对“年/日/时间是什么?”这个问题给出正确/唯一的答案。这取决于问题在世界的哪个地方提出:纽约的情况与悉尼的情况不同。但您的 DateTimeFormatter 正在问这个问题。这就是为什么你会得到一个UnsupportedTemporalTypeException.

您必须至少将 转换Instance为 a :LocalDateTime

System.out.println(timestampFormatter.format(
    LocalDateTime.ofInstant(fileTime.toInstant(), ZoneId.systemDefault()));
Run Code Online (Sandbox Code Playgroud)