在 Java 中将字符串解析为 LocaDateTime
考虑一个字符串“2022-03-23 21:06:29.4933333 +00:00”
。 如何在 Java 中将上面的 DateTimeOffset 字符串解析为 LocalDateTime?
我尝试使用以下 DateTimeFormatter 但格式似乎不正确:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss\[.nnnnnnn\] \[+|-\]hh:mm\]");
LocalDateTime dateTime = LocalDateTime.parse(timestamp, formatter)
Consider a String "2022-03-23 21:06:29.4933333 +00:00"
.
How do I parse the above DateTimeOffset String to LocalDateTime in Java?
I tried with the following DateTimeFormatter but the format seems to be incorrect:
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss\[.nnnnnnn\] \[+|-\]hh:mm\]");
LocalDateTime dateTime = LocalDateTime.parse(timestamp, formatter)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,首先使用 JavDocs for
DateTimeFormatter
手头的,这将真正帮助确定您需要哪些说明符首先要做的是将文本解析为
ZonedDateTime
、LocalDateTime
不会解析带有时区的输入值(AFAIK),您“可能”能够强制它,但有什么意义呢?这将打印...
现在您可以使用
ZonedDateTime#toLocalDateTime
,但这不会考虑用户/计算机的当前时区。如果您需要将
ZonedDateTime
转换为LocalDateTime
,最好立即执行此操作,这将转换时间(如果需要,还可以转换日期)以最好地表示当前的时间时区(好吧,我打字很困惑)例如,将输入值转换为我当前的时区(+11 小时)将如下所示...
它将打印...
这意味着在晚上 9:06 3月23日格林奇(格林尼治标准时间),那是我住的地方 3 月 24 日上午 8 点 06 分。
现在,您可以使用不同的
ZoneId
转换为TimeZone
,它不是当前计算机TimeZone
,但我将把它留给您进行实验(例如,我使用 将 ZonedDateTime 转换为时区的 LocalDateTime 作为我的示例的基础)First, start by having the JavDocs for
DateTimeFormatter
at hand, this is going to really help determine which specifiers you needThe first thing to do is parse the text into a
ZonedDateTime
,LocalDateTime
won't parse a input value with a time zone (AFAIK), you "might" be able to force it, but what's the point?This prints...
Now you could use
ZonedDateTime#toLocalDateTime
, but this won't take into account the current time zone of the user/computer.If you need to convert the
ZonedDateTime
toLocalDateTime
, it's best to do so in away which will translate the time (and date if required) to best represent the time within the current time zone (okay, I was confused typing it)For example, converting the input value into my current time zone (+11 hours) would look like this...
which will print...
This means that at 9:06pm on the 23rd March in Grinch (GMT), it was 8:06am on the 24th March where I live.
Now you can use different
ZoneId
s to convert to aTimeZone
which is not the current computersTimeZone
, but I'll leave that up to you to experiment with (for example, I used Convert ZonedDateTime to LocalDateTime at time zone to base my example on)您需要创建自定义 DateTimeFormatter:
You need create custom DateTimeFormatter: