How to set the value of a JSpinner using a LocalTime object?

Tags: , , , ,



I am trying to make a time picker using JSpinner and Java 8’s time API. I want to make a time picker without date.

Before, I was using SimpleDateFormat, but that would return time with date when I print out the value of the JSpinner.

So how can I pass the value of a LocalTime object into the setValue method of a JSpinner?

Here is my current code:

JSpinner timeSpinner = new JSpinner(new SpinnerDateModel());
JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(timeSpinner, "HH:mm");
timeSpinner.setEditor(timeEditor);
LocalTime newTime = LocalTime.of(11, 9);
timeSpinner.setValue(newTime);
        
timeSpinner.setBounds(126, 55, 56, 22);
contentPanel.add(timeSpinner);

Or am I taking the wrong approach to this?

This is my original code which works:

JSpinner timeSpinner = new JSpinner(new SpinnerDateModel());
JSpinner.DateEditor timeEditor = new JSpinner.DateEditor(timeSpinner, "HH:mm");
timeSpinner.setEditor(timeEditor);
SimpleDateFormat time = new SimpleDateFormat("HH:mm");
try {
    timeSpinner.setValue(time.parseObject("10:00"));
} catch (ParseException timeError) {
    timeError.printStackTrace();
}
timeSpinner.setBounds(126, 55, 56, 22);
contentPanel.add(timeSpinner);

Answer

Yes, method getValue(), of class SpinnerDateModel, returns an instance of java.util.Date() but you can convert that into a LocalTime as follows:

Object obj = timeSpinner.getValue();
if (obj instanceof java.util.Date) {
    java.util.Date theDate = (java.util.Date) obj;
    java.time.Instant inst = theDate.toInstant();
    java.time.ZoneId theZone = java.time.ZoneId.systemDefault();
    java.time.LocalTime thetime = java.time.LocalTime.ofInstant(inst, theZone); // Since JDK 9
    /*
    LocalTime.from(ZonedDateTime.ofInstant(inst, theZone)); // Since JDK 8
     */
    System.out.println(thetime);
}

As you can see, there are two ways to convert java.util.Date to LocalTime, depending on which JDK version you are using.

The above code will print theTime in format HH:mm



Source: stackoverflow