在 Java 8 中将日期转换为 EST

Nom*_*tar 4 java

我正在尝试将日期转换为以下时区,但结果不符合预期 - 我得到的要求是说例如从PMST转换为EST输出应该少 2 小时。

PMST、NST、AST、EST、CST、MST、PST、AKST、HAST

String inputDate = "2017/04/30 08:10";
DateTimeFormatter sourceFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm");
LocalDateTime local = LocalDateTime.parse(inputDate, sourceFormatter);
ZonedDateTime zoned = local.atZone(TimeZone.getTimeZone("PMST").toZoneId());
ZonedDateTime requiredZone = zoned.withZoneSameInstant(TimeZone.getTimeZone("EST").toZoneId());
System.out.println(requiredZone);
Run Code Online (Sandbox Code Playgroud)

输出- 2017-04-30T03:10-05:00

Bas*_*que 6

避免伪区域

切勿使用3-4个字母缩写常常见诸媒体,如CSTISTEST。这些不是真正的时区,不是标准化的,甚至不是唯一的(!)。

真实时区: continent/region

相反,请确定您打算使用的真实时区。时区的名称格式continent/regionAmerica/MontrealandAfrica/CasablancaPacific/Auckland

更改您的输入以符合 ISO 8601 标准格式。

String input = "2017/04/30 08:10".replace( " " , "T" ) ;
Run Code Online (Sandbox Code Playgroud)

解析为 a ,LocalDateTime因为您的输入缺少从 UTC 或时区偏移的指标。

LocalDateTime ldt = LocalDateTime.parse( input ) ;
Run Code Online (Sandbox Code Playgroud)

如果您确定它是用于此输入,则应用时区。

ZoneId z = ZoneId.of( "America/New_York" ) ;
ZonedDateTime zdt = ldt.withZoneSameInstant( z ) ;
Run Code Online (Sandbox Code Playgroud)


Sar*_*ngh 4

所以您知道您输入的“本地日期”位于 PMST 时区。

String localDateTimeString = "2017/04/30 08:10";
Run Code Online (Sandbox Code Playgroud)

但你应该能够注意到,上面的内容并没有携带你所知道的时区信息。因此,您需要将该信息添加到字符串中。

但我们现在拥有的只是一个String,所以首先我们必须决定我们将使用的日期时间格式,并且它必须是时区感知的,

DateTimeFormatter dateTimeWithZoneFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm Z");
Run Code Online (Sandbox Code Playgroud)

这里,Z代表时区偏移。我们知道PMSTUTC-0300,所以我们需要将此信息添加到我们的本地时间字符串中,

String dateTimeString = "2017/04/30 08:10" + " -0300";
Run Code Online (Sandbox Code Playgroud)

现在,我们可以使用日期时间格式化程序来读取它,

ZonedDateTime dateTimeInPMST = ZonedDateTime.parse(dateTimeString, dateTimeWithZoneFormatter);
Run Code Online (Sandbox Code Playgroud)

现在我们可以获取任何我们想要的时区的日期,

ZonedDateTime dateTimeInEST = dateTimeInPMST.withZoneSameInstant(TimeZone.getTimeZone("EST").toZoneId());
Run Code Online (Sandbox Code Playgroud)

编辑 1::

获取时区的偏移量(比如说EST

int offsetInSeconds = TimeZone.getTimeZone("EST").getRawOffset() / 1000;

ZoneOffset zoneOffset = ZoneOffset.ofTotalSeconds(offsetInSeconds);

String zoneOffsetString = zoneOffset.toString();
// "-05:30"
Run Code Online (Sandbox Code Playgroud)

:请注意-05:30,我们将不得不更改我们的DateTimeFormat以适应这一点,

DateTimeFormatter dateTimeWithZoneFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm ZZZ");
Run Code Online (Sandbox Code Playgroud)

现在,您可以将其添加到任何 dateTimeString,

public String makeOffsetAwareDateTimeString(String dateTimeString, String timezone) {
    int offsetInSeconds = TimeZone.getTimeZone(timezone).getRawOffset() / 1000;
    ZoneOffset zoneOffset = ZoneOffset.ofTotalSeconds(offsetInSeconds);
    String zoneOffsetString = zoneOffset.toString();
    return dateTimeString + " " + zoneOffsetString;
}
Run Code Online (Sandbox Code Playgroud)