java zoneddatetime toEpochSecond而不转换为本地时间

问题描述

我有一个处于EST时间且没有夏令时的数据集。 从字符串中读取每个日期时间,并使用

创建一个zoneddatetime
zoneddatetime java.time.zoneddatetime.of(int year,int month,int dayOfMonth,int hour,int minute,int second,int nanoOfSecond,ZoneId zone)

具有ZoneId.of(“ America / New_York”);

我需要将这些转换为一个纪元,但是内置的toEpochSecond方法转换为我的本地时间,即夏令时,即BST。结果,时间戳会根据一年中的时间而减少四到五个小时。有没有一种方法可以获取不考虑任何本地时间的unix时间戳,因此该时间戳与原始字符串中的datetime相匹配?

解决方法

我需要将它们转换为一个纪元,但内置 toEpochSecond方法转换为我的本地时间,即BST与天 省电。结果,时间戳减少了四到五个小时 取决于一年中的时间。

您必须做的是根本错误的事情。检查以下代码的输出,您将发现没有区别。

import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        // Formatter ignoring nanoseconds
        DateTimeFormatter formatter = new DateTimeFormatterBuilder()
                                        .appendPattern("uuuu-MM-dd'T'HH:mm:ssXXX")
                                        .optionalStart()
                                        .appendLiteral('[')
                                        .parseCaseSensitive()
                                        .appendZoneRegionId()
                                        .appendLiteral(']')
                                        .toFormatter(Locale.ENGLISH);

        // The given time-zone
        ZoneId zone = ZoneId.of("America/New_York");

        ZonedDateTime zdtNow = ZonedDateTime.now(zone);
        System.out.println(zdtNow.format(formatter));

        // Epoch seconds from ZonedDateTime
        long epochSecond = zdtNow.toEpochSecond();
        System.out.println(epochSecond);

        // ZonedDateTime from epoch seconds
        ZonedDateTime zdtFromEpochSeconds = Instant.ofEpochSecond(epochSecond).atZone(zone);
        System.out.println(zdtFromEpochSeconds.format(formatter));
    }
}

输出:

2020-09-28T17:31:23-04:00[America/New_York]
1601328683
2020-09-28T17:31:23-04:00[America/New_York]
,

要将ZonedDateTime转换为Unix纪元时间戳

首先将其转换为java.time.Instant,然后将区域偏移设置为UTC,然后再将其转换为纪元秒,如下所示:

zonedDateTime.toInstant().atZone(ZoneOffset.UTC).toEpochSecond();

注意:变量zonedDateTime的类型为java.time.ZonedDateTime,可以在任何时区(以秒为单位)转换为“ Unix纪元时间戳”之前。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...