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

DateTimeFormatter - parsing string with time zone

我有一个 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。