java - DateTimeFormatter - 解析带有时区的字符串

标签 java time

我有一个 JSpinner 用于选择特定时间(今天的日期),我需要将字符串结果转换为 LocalDateTime 实例。但是,我似乎无法正确编写正则表达式字符串。你能告诉我我做错了什么吗?

JSpinner:

        SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
        spinnerStart = new JSpinner(sm);
        JSpinner.DateEditor de = new JSpinner.DateEditor(spinnerStart, "hh:mm");
        spinnerStart.setEditor(de);

当使用 spinnerStart.getValue().toString() 检查值时,我得到以下信息:

Mon May 25 12:21:24 CEST 2015

我正在尝试根据 this 解析字符串文档但出现异常:

SEVERE [global]
java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {MinuteOfHour=21, MilliOfSecond=0, NanoOfSecond=0, HourOfAmPm=0, MicroOfSecond=0, SecondOfMinute=24},ISO,Europe/Paris resolved to 2015-05-25 of type java.time.format.Parsed
    at java.time.LocalTime.from(LocalTime.java:409)
    at java.time.LocalDateTime.from(LocalDateTime.java:457)

这是我目前的进度:

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd hh:mm:ss zzzz yyyy");
LocalDateTime startTime = LocalDateTime.parse(spinnerStart.getValue().toString(), dtf);

我尝试使用“V”而不是“z”以及其他一些带有偏移量的选项,但似乎无法弄清楚。感谢您提供任何提示。

最佳答案

因此,您有一个 java.util.Date 对象,它表示时间线上的一个精确时刻。要将其转换为 LocalDateTime,您需要将日期转换为字符串,然后解析该字符串。

这是一个糟糕的策略。你不应该那样做。

只需使用日期转换方法:

LocalDateTime localDateTime = 
    date.toInstant()
        .atZone(ZoneId.systemDefault())
        .toLocalDateTime();

当然,如果您想要其他时区的值而不是默认时区,则需要传递适当的 ZoneId。

关于java - DateTimeFormatter - 解析带有时区的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30436231/

相关文章:

c# - 在 .NET 中乘以 TimeSpan

sql - 从长时间的postgres转换日期

java - 访问数组列表中对象的元素

java - 由 : org. hibernate.MappingException 引起:在以下位置找到元素的重复属性映射

javascript - JS - 移动图像,暂停设定时间,然后将图像移回

c++ - 用于记录时间戳的不同 C++ 时钟的优缺点是什么?

ios - 根据一天中的时间采取行动?

java - maven-shade-plugin 和自定义打包类型

JavaFX检测同时按下的多个键盘按键

java - 遍历大型 7*7 矩阵内的 3* 3 子矩阵时绑定(bind)异常错误的数组索引