我正在尝试打印当前系统日期和时间,如下所示,
public class PrintDate {
public void getDate(){
while(true){
System.out.println(new Date());
}
}
public static void main(String[] args) {
new PrintDate().getDate();
}
}
这个无限循环按预期打印当前系统时间戳,当我在操作系统中更改日期或时间但不更改时区时,它工作正常..
示例:
- 我启动了上面的代码,它按预期连续打印当前系统时间戳。
- 当我更改系统日期或时间时,它成功地反射(reflect)在代码中。
- 当我更改系统时区时,它没有反射(reflect)在代码中。自程序启动以来,它仍然显示相同的时区。
我可以知道这背后的原因吗?
最佳答案
时区是进程环境的一部分。为您的系统更改全局时区只会影响新进程。
另见 How to set time zone of a java.util.Date? :
Be aware that java.util.Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.
As ZZ Coder shows, you set the timezone on the DateFormat object, to tell it in which timezone you want to display the date and time.
关于java - 使用 JAVA 中的日期类处理时区更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35312361/