java 使用特定模式将 Instant 格式化为字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37493117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Formatting Instant to String with specific pattern
提问by RandomQuestion
I'm trying to format Instant
to String
with a specific format. Based on the question here Format Instant to String, I'm doing this -
我试图格式Instant
,以String
与特定的格式。基于这里的问题Format Instant to String,我正在这样做 -
DateTimeFormatter formatter = DateTimeFormatter
.ofPattern("YYYY-MM-DD'T'hh:mm'Z'")
.withZone(ZoneOffset.UTC);
// Fails for current time with error 'Field DayOfYear cannot be printed as the
// value 148 exceeds the maximum print width of 2'
LocalDateTime
.ofInstant(Instant.now(), ZoneOffset.UTC)
.format(DATE_TIME_FORMATTER);
// But works for smaller values of Instant
LocalDateTime
.ofInstant(Instant.ofEpochMilli(604800000), ZoneOffset.UTC)
.format(DATE_TIME_FORMATTER));
Any suggestions on why is this happening?
关于为什么会发生这种情况的任何建议?
Thanks
谢谢
回答by Andreas
Pattern YYYY-MM-DD'T'hh:mm'Z'
is wrong:
模式YYYY-MM-DD'T'hh:mm'Z'
错误:
YYYY
- week-based-year wrong: useuuuu
yearMM
- month-of-yearDD
- day-of-year wrong: usedd
day-of-monthhh
- clock-hour-of-am-pm (1-12) without AM/PM you probably wantHH
hour-of-day (0-23)mm
- minute-of-hour
YYYY
- 基于周的年份 错误:使用uuuu
年份MM
- 每年的月份DD
- 年日 错误:使用dd
月日hh
-clock-hour-of-am-pm (1-12) 没有 AM/PM 您可能想要HH
一天中的小时 (0-23)mm
- 分时
It's weird, because you even referenced a link that had the right pattern characters. Unless of course you thought upper- vs lower-case didn't matter, but if so, how did you think MM
(month) vs mm
(minute) worked?
这很奇怪,因为您甚至引用了具有正确模式字符的链接。当然,除非您认为大写与小写无关紧要,但如果是这样,您认为MM
(月)与mm
(分钟)如何工作?
You might want to actually read the documentation.
您可能想要实际阅读文档。
回答by T. Claverie
Take a look at the documentation of the DateTimeFormatter. So, D
stands for the day of the year, while d
is the day of the month, which is what you want.
查看DateTimeFormatter的文档。因此,D
代表一年d
中的第几天,而代表月份中的第几天,这就是您想要的。
Plus, there are several formats that are already defined. The one you want is almost like DateTimeFormatter.ISO_INSTANT
.
另外,已经定义了几种格式。你想要的几乎就像DateTimeFormatter.ISO_INSTANT
.