Java Swing How to - Format date value from JSpinner








Question

We would like to know how to format date value from JSpinner.

Answer

import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/* w  w  w.  j a va  2  s.c o m*/
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;

public class Main {
  String[] zones = { "Asia/Tokyo", "Asia/Hong_Kong", "Asia/Calcutta",
      "Europe/Paris", "Europe/London", "America/New_York",
      "America/Los_Angeles" };
  JLabel[] labels = new JLabel[zones.length];
  SimpleDateFormat[] formats = new SimpleDateFormat[zones.length];
  JSpinner spinner;
  SpinnerDateModel model = new SpinnerDateModel();
  SimpleDateFormat format;
  JPanel panel;
  JFrame frame = new JFrame();

  public Main() {
    Calendar cal = Calendar.getInstance();
    Date date = cal.getTime();
    model.setValue(date);
    spinner = new JSpinner(model);
    spinner.addChangeListener(e -> {
      Date d = (Date) ((JSpinner) e.getSource()).getValue();
      for (int i = 0; i < labels.length; i++) {
        labels[i].setText(formats[i].format(d));
      }
    });
    format = ((JSpinner.DateEditor) spinner.getEditor()).getFormat();
    format.setTimeZone(TimeZone.getTimeZone(zones[0]));
    format.applyPattern("yyyy-MM-dd HH:mm:ss");
    format.applyPattern("HH:mm:ss");
    panel = new JPanel(new GridLayout(zones.length, 2, 10, 10));
    for (int i = 0; i < zones.length; i++) {
      formats[i] = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
      formats[i] = new SimpleDateFormat("HH:mm:ss");
      formats[i].setTimeZone(TimeZone.getTimeZone(zones[i]));
      JLabel label = new JLabel(zones[i]);
      labels[i] = new JLabel(formats[i].format(date));
      labels[i].setHorizontalAlignment(JLabel.RIGHT);
      panel.add(label);
      panel.add(labels[i]);
    }
    frame.setLayout(new BorderLayout(10, 10));
    frame.add(spinner, BorderLayout.NORTH);
    frame.add(panel, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    new Main();
  }
}