将utc时间转换为cst时间



我有一个表示UTC时间的字符串("2021-11-05T22:33:10Z"(。我需要得到等效的cst时间("2021-11-05T16:33:10Z"(。我有下面的代码,但它返回时间为2021-11-05T17:33:10Z。为什么最后的时间加了一个小时?

public class MyClass {
public static void main(String args[]) throws ParseException {
String busDate = "2021-11-05T22:33:10Z";
SimpleDateFormat currentFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
currentFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date utcTime = currentFormat.parse(busDate);

System.out.println(utcTime); //Fri Nov 05 22:33:10 GMT 2021

SimpleDateFormat updateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
updateFormat.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
String formattedDateTime = updateFormat.format(utcTime);
System.out.println(formattedDateTime); //2021-11-05T17:33:10Z

}
}

tl;dr

你问:

为什么最后的时间会增加一个小时?

您的期望值不正确。夏令时于5日在该地区生效。

2021-11-05T22:33:10Z=2021-11-5T17:33:10-05:00[美国/芝加哥]

仅使用java.time

您使用的是糟糕的日期-时间类,这些类在几年前被JSR310中定义的现代java.time类所取代。

UTC时刻

Instant instant = Instant.parse( "2021-11-05T22:33:10Z" ) ;

instant.toString((:2021-11-05T22:33:10Z

从UTC调整到时区

ZoneId z = ZoneId.of( "America/Chicago" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;

zdt.toString((:2021-11-05T17:33:10-05:00[美国/芝加哥]

请注意,您对2021-11-05T16:33:10Z结果的期望是不正确的11月5日,在夏令时(DST(下,芝加哥时间比UTC晚了五个小时,而不是六个小时。夏令时于2021年11月7日结束。在11月剩下的时间里,芝加哥时间比UTC晚了6个小时。

请在IdeOne.com上实时查看此代码。

实时区域名称

不存在cstCST这样的时区。对一些人来说,这意味着中央标准时间,对更多的人来说,意味着中国标准时间。使用这些2-4个字母的伪区域仅用于向用户演示时的本地化,而不用于数据交换。在后台,只使用Continent/Region格式的实时区域。

对于数据交换,只能使用ISO 8601标准格式。

最新更新