英文:
How to show timezone with hours and minutes with DateTimeFormatter?
问题
我需要获取当前时间的字符串,格式如下:2019-12-24T09:20:35.8062135+03:00
我不明白时区应该怎么处理。我的实现如下:
yyyyMMdd'T'HH:mm:ss.SSSSSSX
末尾没有零。我应该如何正确实现?
代码如下:
val FORMATTER: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HH:mm:ss.SSSSSSX")
println(ZonedDateTime.now().format(FORMATTER))
英文:
I need to get string of current time in format like this: 2019-12-24T09:20:35.8062135+03:00
I can't understand what to do with timezone. My implementation:
yyyyMMdd'T'HH:mm:ss.SSSSSSX
It's without zeroes in the end. How can I do it correctly?
The code:
val FORMATTER: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HH:mm:ss.SSSSSSX")
println(ZonedDateTime.now().format(FORMATTER))
答案1
得分: 2
如 https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html 中提到的,一个字母 X 只会输出小时偏移。两个 X 还会输出分钟,但没有冒号分隔。要获取分钟和冒号分隔,您应该使用 3 个 X:
val FORMATTER: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HH:mm:ss.SSSSSSXXX")
println(ZonedDateTime.now().format(FORMATTER))
英文:
As mentioned in https://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html the one letter X will only output the hour offset only. Two Xs will output also the minutes but without colon separation. To get the minutes as well colon separation you should use 3 Xs:
val FORMATTER: DateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd'T'HH:mm:ss.SSSSSSXXX")
println(ZonedDateTime.now().format(FORMATTER))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论