user3763216 user3763216 - 11 months ago 107
Java Question

How to set value of JSpinner from string?

I currently am using a JSpinner to set a time value which is then updated to my database as a varchar e.g. 12:00:00 AM. However in another form I would like to retrieve this time that was added into my database into the JSpinner in my update form. The update form is for the user to update the time that they have selected before (e.g. 12:00:00 AM like stated above). Right now the default time value is the current time. I tried to use the .setValue() method but it is an illegal value as my retrieved time is a String. Here is my code to make things clearer:

shiftTime = new JSpinner(new SpinnerDateModel());
JSpinner.DateEditor de_shiftTime = new JSpinner.DateEditor(shiftTime,
"hh:mm:ss a");
shiftTime.setSize(108, 22);
shiftTime.setLocation(436, 478);

The .getVolDutyShift() method returns a string (12:00:00 AM in string format)
a is my object which calls the .getVolDutyShift() method.
How should I parse this a.getVolDutyShift() so the JSpinner will load the time as the time in my database (12:00:00 AM)?

Answer Source

Try this out. It will convert your time in string to java.sql.Time.

    SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss a");
    java.util.Date d =(java.util.Date)format.parse(a.getVolDutyShift());
    java.sql.Time time = new java.sql.Time(d.getTime());
    shiftTime.setValue(time );

But you should always save date and time in their original data types in database and not as varchar