当我写这段代码时:
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.注意:我尝试过使用IST和ist字符串。对于IST字符串,它提供Indian Standard Time;对于ist,它提供Greenwich Mean Time
发布于 2012-11-05 19:59:10
简而言之,是的,它区分大小写。
按照您的示例,ist将为您提供GMT,因为无法找到具有此类ID的时区,从而为您提供默认结果
它可以与est (GMT-05:00是EASTERN STANDARD TIME)一起工作,因为两个if都是已知的,但我不会指望它(不太确定如果更换平台,它还会在那里)。
此外,正如API所告诉的,您不应该使用这些缩写ID,而应该直接使用全名或自定义ID。
您可以使用TimeZone.getAvailableIDs()获得您的平台的可用ID列表,然后您可以选择正确的ID。
我自己会考虑使用GMT-5:00格式,在我看来,它更具可读性,也不容易出错。
发布于 2015-05-09 05:28:22
getTimeZone(String id)的实现实际上从JDK7更改为8。
在JDK7中,"est“实际上返回一个id为"est”的timeZone。在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());
}https://stackoverflow.com/questions/13230937
复制相似问题