如何使用DateTimeFormatter显示时区的小时和分钟?

huangapple go评论91阅读模式
英文:

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))

huangapple
  • 本文由 发表于 2020年7月31日 15:50:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/63187857.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定