How to get only Hour and Minute of JSpinner?

Jimmy picture Jimmy · Mar 22, 2013 · Viewed 10.9k times · Source

I have a JSpinner. When i usespinner.getValue()it gives me Sun Mar 24 01:11:41 PDT 2013 but i want to have only Hour and Minute in 24 hour format

Date date = new Date();
        SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.MINUTE);

        JSpinner spinner = new JSpinner(sm);
        JSpinner.DateEditor de = new JSpinner.DateEditor(spinner, "hh:mm a");
        spinner.setEditor(de);
        if ( spinner.getEditor() instanceof JSpinner.DefaultEditor ) 
        {
                  JSpinner.DefaultEditor editor = ( JSpinner.DefaultEditor ) spinner.getEditor();
                  editor.getTextField().setEnabled( true );
                  editor.getTextField().setEditable( false );
        }

        System.out.println("Spinner:      "+spinner.getValue());

Answer

kleopatra picture kleopatra · Mar 22, 2013

Extracting the meat from @mKorbel's answer:

System.out prints the value object uing its toString method, if you want to print it formatted you need to use a Formatter, f.i. the one used by the editor in your code:

Date date = new Date();
SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.MINUTE);

JSpinner spinner = new JSpinner(sm);
JSpinner.DateEditor de = new JSpinner.DateEditor(spinner, "hh:mm a");
de.getTextField().setEditable( false );
spinner.setEditor(de);

System.out.println("Spinner:      "+de.getFormat().format(spinner.getValue()));