DateTimeFormatter - 使用时区解析字符串

时间:2015-05-25 10:28:58

标签: java time

我有一个JSpinner用于选择特定时间(今天的日期),我需要将String结果转换为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'以及其他一些偏移的选择,但似乎无法弄明白。感谢您的任何提示。

1 个答案:

答案 0 :(得分:4)

所以,你有一个java.util.Date对象,代表时间线上的精确瞬间。要将其转换为LocalDateTime,您将Date转换为String,然后解析String。

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

只需使用日期转换方法:

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

当然,如果您想要另一个时区的值而不是默认值,则需要传递相应的ZoneId。