java 中的递增计时器不是从 0 开始的
Count up timer in java not starting from 0
我创建了一个用于 java 秋千 window 的计时功能。问题是时间不是从零开始计数的。当我启动计时器时,初始时间总是提前一个小时。
这是我的代码:
public static void timeRecording(){
Date startTime = new Date();
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss");
Date actualTime = new Date();
String dateToPrint = timeFormat.format(new Date(actualTime.getTime() - startTime.getTime()));
//String dateToPrint = timeFormat.format(actualTime);
System.out.println(actualTime);
//actualTime
// String timeToPrint.timeFormat = actualTime;
timerLabel.setText(dateToPrint);
}
};
new Timer(delay, taskPerformer).start();
}
这是开始时显示的时间:
发生的情况是,如果日期之间的差异为一秒,则:new Date(actualTime.getTime() - startTime.getTime())
在 1970 年 1 月 1 日 00:01 UTC 创建一个日期。
但是当您格式化它时,DateFormat 使用您的时区 (Lisbon = UTC+1) 并将日期视为 1970 年 1 月 1 日 01:01 UTC+1。
如果要得到正确的输出,需要设置格式化程序的时区:
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(fmt.format(new Date(0))); //outputs 00:00:00 as expected
注意:正确的格式模式是 HH (0-23),而不是 hh(即 1-12)。
您的 "hh:mm:ss"
的 SimpleDateFormat
使用 h
,在 JavaDoc 中描述为:
h Hour in am/pm (1-12)
因此您的时间将始终从 1
开始。
您可以尝试使用
K Hour in am/pm (0-11)
即"KK:mm:ss"
我创建了一个用于 java 秋千 window 的计时功能。问题是时间不是从零开始计数的。当我启动计时器时,初始时间总是提前一个小时。
这是我的代码:
public static void timeRecording(){
Date startTime = new Date();
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
SimpleDateFormat timeFormat = new SimpleDateFormat("hh:mm:ss");
Date actualTime = new Date();
String dateToPrint = timeFormat.format(new Date(actualTime.getTime() - startTime.getTime()));
//String dateToPrint = timeFormat.format(actualTime);
System.out.println(actualTime);
//actualTime
// String timeToPrint.timeFormat = actualTime;
timerLabel.setText(dateToPrint);
}
};
new Timer(delay, taskPerformer).start();
}
这是开始时显示的时间:
发生的情况是,如果日期之间的差异为一秒,则:new Date(actualTime.getTime() - startTime.getTime())
在 1970 年 1 月 1 日 00:01 UTC 创建一个日期。
但是当您格式化它时,DateFormat 使用您的时区 (Lisbon = UTC+1) 并将日期视为 1970 年 1 月 1 日 01:01 UTC+1。
如果要得到正确的输出,需要设置格式化程序的时区:
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm:ss");
fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println(fmt.format(new Date(0))); //outputs 00:00:00 as expected
注意:正确的格式模式是 HH (0-23),而不是 hh(即 1-12)。
您的 "hh:mm:ss"
的 SimpleDateFormat
使用 h
,在 JavaDoc 中描述为:
h Hour in am/pm (1-12)
因此您的时间将始终从 1
开始。
您可以尝试使用
K Hour in am/pm (0-11)
即"KK:mm:ss"