Reputation: 8015
I have a JSpinner for selecting specific time (with today's date) and I need to convrert the String result into LocalDateTime
instance. However, I can't seem to write the regex string right. Could you tell me what am I doing wrong, please?
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);
When checking the value with spinnerStart.getValue().toString()
, I get the following:
Mon May 25 12:21:24 CEST 2015
I am trying to parse the string according to this documentation but am getting an exception:
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)
This is my progress so far:
DateTimeFormatter dtf = DateTimeFormatter.ofPattern("EEE MMM dd hh:mm:ss zzzz yyyy");
LocalDateTime startTime = LocalDateTime.parse(spinnerStart.getValue().toString(), dtf);
I tried using 'V' instead of 'z' and some other choices with offsets as well but cannot seem to figure it out. Thanks for any tips.
Upvotes: 3
Views: 688
Reputation: 692231
So, you have a java.util.Date
object, which represents a precise instant on the time-line. And to transform it into a LocalDateTime, you're transforming the Date into a String, and then parse the String.
That's a bad strategy. You shouldn't do that.
Just use the date transformation methods:
LocalDateTime localDateTime =
date.toInstant()
.atZone(ZoneId.systemDefault())
.toLocalDateTime();
Of course, if you want the value for another time zone than the default one, you'll need to pass the appropriate ZoneId.
Upvotes: 5