java - 使用 JAVA 中的日期类处理时区更改

标签 java date datetime

我正在尝试打印当前系统日期和时间,如下所示,

public class PrintDate {

    public void getDate(){
        while(true){
            System.out.println(new Date());
        }
    }

    public static void main(String[] args) {
       new PrintDate().getDate();
    }
}

这个无限循环按预期打印当前系统时间戳,当我在操作系统中更改日期或时间但不更改时区时,它工作正常..

示例:

  1. 我启动了上面的代码,它按预期连续打印当前系统时间戳。
  2. 当我更改系统日期或时间时,它成功地反射(reflect)在代码中。
  3. 当我更改系统时区时,它没有反射(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/

相关文章:

java - LIKE - hibernate 命名查询

java - Java中将一长串日期和时间转换为时间戳格式

datetime - 在 JPA2 (JPQL) 中仅比较日期(无时间)

c# - 如果 DateTime 是不可变的,为什么下面的工作?

java - 如何在使用SAXParser解析XML中添加AsyncTask?

java - Spring IO POST 表单重定向到错误的 URL - Thymeleaf

java - 为我的 jar 文件提供更多内存

powershell - PowerShell今天的日期为4-15-2020(获取日期).AddMonths(-6).month)预计为4-15-2019,获得10/31/2020

javascript - 为什么 Date.prototype.toString() 和 Date.prototype.toLocaleString() 会返回表示不一致时间点的字符串?

java - 如果超出特定时区,如何捕获基于 UTC 的事件?