【发布时间】:2016-09-23 11:32:59
【问题描述】:
我正在对使用 java 日期和 Swing 的 JSpinner 作为 DateEditor 的现有 Swing 应用程序进行错误修复。我试图让编辑器默认使用 UTC 来显示时间,而不是我们的本地时区。该应用程序在 Windows 上运行,使用 Java 8。
我使用的代码如下。
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.SpinnerDateModel;
public class Test {
public static void main(String [] args) {
// Initialize some sample dates
Date now = new Date(System.currentTimeMillis());
JSpinner spinner = new JSpinner();
// Create model with a current date and no start/end date boundaries, and set it to the spinner
spinner.setModel(new SpinnerDateModel(now, null, null, Calendar.MINUTE));
// Create new date editor with a date format string that also displays the timezone (z)
// Set the format's timezone to be UTC, and finally set the editor to the spinner
JSpinner.DateEditor startTimeEditor = new JSpinner.DateEditor(spinner, "yyyy-MMM-dd HH:mm zzz");
startTimeEditor.getFormat().setTimeZone(TimeZone.getTimeZone("UTC"));
spinner.setEditor(startTimeEditor);
JPanel panel = new JPanel();
panel.add(spinner);
JOptionPane.showConfirmDialog(null, panel);
}
}
但是,此代码存在初始化问题。当对话框第一次出现时,时间显示在我们当地的时区,而不是 UTC。一旦用户第一次通过单击它与该字段进行交互,它就会切换到 UTC 并从那里开始正常工作。
如何让该字段最初以 UTC 时间显示?
【问题讨论】: