给定一个FileTime fileTime,如何以自定义的方式将其格式化为字符串?
String s = fileTime.toString()仅以ISO格式提供。
String s = DateTimeFormatter.ofPattern("uuuu-MMM-dd HH:mm:ss")
.format(fileTime.toInstant());抛出UnsupportedTemporalTypeException: Unsupported field: Year
发布于 2015-10-30 05:20:09
不能使用查询年份的DateTimeFormatter实例格式化Instant。
Instant表示时间线上的单个点。这就是为什么不可能给出正确的/独特的答案来回答“年份/日期/时间是多少?”。这取决于世界上的问题是在哪里提出的:在纽约,它与西德尼不同。但是你的DateTimeFormatter正在问这个问题。这就是为什么你会得到一个UnsupportedTemporalTypeException。
您必须至少将Instance转换为LocalDateTime:
System.out.println(timestampFormatter.format(
LocalDateTime.ofInstant(fileTime.toInstant(), ZoneId.systemDefault()));发布于 2015-10-30 14:56:59
就我个人而言,我发现错误信息“不支持的字段:年份”具有误导性。真正的原因是缺少时区。需要这些信息来帮助格式化程序在内部将给定的瞬间转换为人工时间表示。解决方案:提供时区。然后支持格式化或解析Instant -与@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解析:
不幸的是,反向过程--解析--并没有以相同的直接方式工作,因为java.time的格式引擎的设计使得格式化程序只返回需要转换为真正需要的类型的原始TemporalAccessor。示例:
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如果要解析的输入包含时区偏移量或标识符,则可以修改模式(符号x、X、z、Z、VV等)。并且省略对withZone(...)的调用,并且在发生偏移的情况下--您确实应该忽略该调用,因为否则格式化程序将不会使用输入的时区偏移量,而是使用所提供的一个区域(我在自己的测试中观察到了一个陷阱)。
发布于 2015-10-30 14:09:32
格式化Instant需要一个时区.这可以使用withZone(ZoneId)来实现。
String s = DateTimeFormatter.ofPattern("uuuu-MMM-dd HH:mm:ss")
.withZone(ZoneId.systemDefault())
.format(fileTime.toInstant());https://stackoverflow.com/questions/33427126
复制相似问题