私は、Java日付とSwingのJSpinnerをDateEditorとして使用している既存のSwingアプリケーションにバグ修正を行っています。私は、ローカルタイムゾーンではなく、UTCを使用して時刻を表示するようにエディタをデフォルトに設定しようとしています。アプリケーションはJava 8を使用してWindows上で動作しています。JavaのJSpinner.DateEditorが初期化時のTimeZoneを尊重しない
私が使用しているコードは以下のとおりです。
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);
}
}
ただし、このコードには初期化の問題があります。 Dialogが最初に表示されると、時間はUTCではなくローカルタイムゾーンで表示されます。ユーザが最初にフィールドをクリックすることでフィールドとやりとりすると、UTCに切り替わり、そこから正しく動作します。
フィールドをUTC時間で最初に表示させるにはどうすればよいですか?
ありがとうございます、私たちが検討している可能性のある回避策です。しかし、それはハックのように思えたので、回避策としてそれを解決する前に、より適切な方法があるかどうかを見たいと思っていました。 – JohnnyO
@ JohnnyO別の回避策を追加しました。残念ながら、それはまだハックです。私は、JSpinnerを標準的に使用すると、エディタの変更に基づいて更新されることはわかりません。 – VGR