我有一个用于选择特定时间(今天的日期)的 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);
Run Code Online (Sandbox Code Playgroud)
使用 来检查值时spinnerStart.getValue().toString(),我得到以下信息:
Mon May 25 12:21:24 CEST 2015
Run Code Online (Sandbox Code Playgroud)
我正在尝试根据此文档解析字符串,但出现异常:
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)
Run Code Online (Sandbox Code Playgroud)
这是我到目前为止的进展:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd hh:mm:ss zzzz yyyy");
LocalDateTime startTime = LocalDateTime.parse(spinnerStart.getValue().toString(), dtf);
Run Code Online (Sandbox Code Playgroud)
我尝试使用 'V' 而不是 'z' 以及其他一些带有偏移量的选项,但似乎无法弄清楚。感谢您提供任何提示。
所以,你有一个java.util.Date对象,它代表时间线上的一个精确时刻。要将其转换为 LocalDateTime,您需要将日期转换为字符串,然后解析该字符串。
这是一个糟糕的策略。你不应该那样做。
只需使用日期转换方法:
LocalDateTime localDateTime =
date.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
Run Code Online (Sandbox Code Playgroud)
当然,如果您想要其他时区的值而不是默认时区,则需要传递适当的 ZoneId。