强制Java 8 LocalTime toString报告省略的值 [英] Forcing Java 8 LocalTime toString to report omitted values
问题描述
我有以下日期时间辅助方法,它将UTC划分的Java 8 日期
转换为日期时间字符串:
I have the following datetime helper method that converts a UTC-zoned Java 8 Date
into a datetime string:
public static String dateTimeString(Date date) {
return date.toInstant().atZone(ZoneId.of("UTC")).toLocalDateTime().toString();
}
所需的结果是总是得到结果字符串格式为:
The desired result is to always have the resultant String be formatted as:
YYYY-MM-dd'T'HH:mm:ss'Z'
YYYY-MM-dd'T'HH:mm:ss'Z'
问题是,Java 8 LocalTime#toString()
故意剥离时间零件的组件。例如,如果我有一个 Date
实例代表 2018年6月8日12:35:00 UTC 。然后上面这个方法的输出是: 2018-06-08'T'12:35'Z'。而我希望它包含任何清零的秒/分/小时组件(例如 2018-06-08'T'12:35:00'Z')。
Problem is, Java 8 LocalTime#toString()
intentionally strips off time components that are zero. So for instance if I have a Date
instance that represents June 8, 2018 at 12:35:00 UTC. Then the output of this method above is: 2018-06-08'T'12:35'Z'. Whereas I want it to contain any zeroed-out second/minute/hour components (e.g. 2018-06-08'T'12:35:00'Z').
任何想法?
推荐答案
private static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssX");
public static String dateTimeString(Date date) {
return date.toInstant().atOffset(ZoneOffset.UTC).format(formatter);
}
只需使用固定格式的模式字符串即可获得所需的格式。让我们试试吧:
Just use a fixed format pattern string to get your desired format. Let’s try it:
System.out.println(dateTimeString(new Date(0)));
System.out.println(dateTimeString(new Date(1_524_560_255_555L)));
这打印:
1970-01-01T00:00:00Z
2018-04-24T08:57:35Z
- 在第一个示例时间内,即使它们为0,也会打印分钟和秒。
- In第二个例子 milliseoncds被省略即使它们非零(你看到我指定的毫秒值在555结束)。
- In the first example hours, minutes and seconds are printed even if they are 0.
- In the second example milliseoncds are omitted even when they are non-zero (you see that the milliseconds value I specified ends in 555).
所有这些都说,无论你有 2018-06-08T12:35Z
,<$ c $,输出都符合ISO 8601格式c> 2018-06-08T12:35:00Z 甚至 2018-06-08T12:35:00.000000000Z
。因此,在您不必定义自己的格式化程序之前,您可能需要再次检查是否遗漏第二个作品。
All of this said, the output conforms to the ISO 8601 format no matter if you have 2018-06-08T12:35Z
, 2018-06-08T12:35:00Z
or even 2018-06-08T12:35:00.000000000Z
. So you may want to check once more whether leaving out the second works for your purpose before you take the trouble of defining your own formatter.
链接: 维基百科文章:ISO 8601
这篇关于强制Java 8 LocalTime toString报告省略的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!