即使您选择任何时区,以秒为单位的时间也是相同的?

Ank*_*wal 1 java timezone datetime epoch

在应用 TimeZone“Europe/Warsaw”后,我使用以下函数以秒为单位获取时间。

我正确获取日期,但是一旦我以秒为单位转换日期,我的输出就会出错。服务器期望时区“欧洲/华沙”中的秒数。摆脱这种困境的最佳方法是什么?

public static long getTimeInSeconds() {
    try {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        //Here you say to java the initial timezone. This is the secret
        sdf.setTimeZone(TimeZone.getTimeZone("Europe/Warsaw"));

        //Will get in Warsaw time zone
        String date = sdf.format(calendar.getTime());

        Date date1 = sdf.parse(date);

        //Convert time in seconds as required by server.
        return (date1.getTime() / 1000);

    } catch (ParseException e) {
        e.printStackTrace();
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

xun*_*nts 5

“时区中的秒数”没有意义,因为纪元秒的意思是“纪元以来的秒数”(其中纪元UTC 中的 1970 年 1 月 1 日午夜),无论时区如何。

这个值在世界各地都是一样的。但是相同的纪元秒值可以转换为本地日期和时间,具体取决于时区。

示例:现在,纪元秒值是 1520352472。这个相同的值(纪元以来的 1520352472 秒),在世界各地都是相同的。但是这个值可以代表每个时区的不同日期和时间:

  • 2018 年 3 月 6 日,UTC 时间 16:07:52
  • 2018 年 3 月 6 日,13:07:52 在圣保罗(巴西)
  • 2018 年3 月7日,东京 01:07:52

问题是:无论我在哪个时区,纪元秒值都将相同,因此您根本不需要考虑任何时区。

java.util.Date没有时区的任何概念,以及,它只是包装了一个long代表,因为毫秒为单位的数值。所以,如果你有一个Date对象,只需使用这个值并除以 1000:

long epochSeconds = new Date().getTime() / 1000;
Run Code Online (Sandbox Code Playgroud)

实际上,如果您想要当前日期/时间的数值,您甚至不需要创建一个Date来获取它:

long epochSeconds = System.currentTimeMillis() / 1000;
Run Code Online (Sandbox Code Playgroud)