TimeZone.setTimeZone("est")和TimeZone.setTimeZone("EST")有区别吗?

3
当我写下这段代码:
   Calendar cal = Calendar.getInstance();
   cal.setTimeZone(TimeZone.getTimeZone("EST"));
   System.out.println(cal.getTimeZone().getDisplayName());

输出结果为:
   Eastern Standard Time

但是当我编写下面的代码时:

   Calendar cal = Calendar.getInstance();
   cal.setTimeZone(TimeZone.getTimeZone("est"));
   System.out.println(cal.getTimeZone().getDisplayName());

我得到的输出是:
   GMT-05:00

在设置TimeZone.setTimeZone(String str)时,使用"EST"和"est"这样的参数有什么区别吗?(调用时传递的str参数是否区分大小写?)

API没有提及任何关于它的信息:

getTimeZone

public static TimeZone getTimeZone(String ID)

Gets the TimeZone for the given ID.

Parameters:  
ID - the ID for a TimeZone, either an abbreviation such as "PST", a full name such as "America/Los_Angeles", or a custom ID such as "GMT-8:00".   
Note that the support of abbreviations is for JDK 1.1.x compatibility only and full names should be used.

Returns:
the specified TimeZone, or the GMT zone if the given ID cannot be understood.

注意:我尝试了 ISTist 字符串。对于 IST 字符串,它会给出 印度标准时间,而对于 ist,它会给出 格林威治平均时间


请给点踩的用户留下评论。 - Abubakkar
2个回答

3

从JDK 7到8,getTimeZone(String id)的实现实际上发生了变化。

JDK 7中,“est”实际上返回一个ID为“est”的时区。在Java 7上运行以下测试用例将成功(并在Java 8上失败):

@Test
public void estTimeZoneJava7() {
    TimeZone timeZone = TimeZone.getTimeZone("est");
    assertEquals("est", timeZone.getID()) ;
}

在Java 8中,时区“est”实际上被处理为未知时区,并且实际上将返回ID为“GMT”的GMT时区。以下测试用例将在Java 8上成功执行(并在Java 7上失败)。

@Test
public void estTimeZoneJava8() {
    TimeZone timeZone = TimeZone.getTimeZone("est");
    assertEquals("GMT", timeZone.getID());
}

3
简而言之,是的,它区分大小写。
根据您的示例,如果找不到具有此ID的时区,则会给您提供默认结果,因此ist会给您提供GMT
使用estGMT-05:00EASTERN STANDARD TIME)可以正常工作,因为两个ID都是已知的,但我不会指望这一点(如果更改平台,不确定是否仍然存在)。
此外,正如API所述,您不应使用那些缩写的ID,而是直接使用全名或自定义ID。
您可以使用TimeZone.getAvailableIDs()获取可用ID列表,然后选择正确的ID。
我本人会考虑使用GMT-5:00格式,我认为这种方式更易读且更少出错。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接