时区.getTimeZone("CST")返回GMT

11

我正在把CST时间转换为本地时间,但是getTimeZone似乎无法正常工作。

    String cstTime = "2013-06-21 14:00:00";

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone("CST"));

    Date date = null;
    try {
        date = simpleDateFormat.parse(cstTime);
    } catch (ParseException e) {
        System.out.println("Parse time error");
        e.printStackTrace();
    }

    TimeZone destTz = TimeZone.getDefault();//here I should get EDT on my phone
    simpleDateFormat.setTimeZone(destTz);
    String convertedLocalTime = simpleDateFormat.format(date);

    //the converted time I get is  "2013-06-21 10:00:00" 
    //but it should be             "2013-06-21 15:00:00" 

在调试时发现它似乎使用的是 GMT 而不是 CST,以下是我得到的信息:

String abc = TimeZone.getTimeZone("CST").toString();
System.out.println("CST:"+abc);
Output:
I/System.out(19404): CST:java.util.SimpleTimeZone[id=GMT,offset=0,dstSavings=3600000,
useDaylight=fals‌​e,startYear=0,startMode=0,startMonth=0,startDay=0,startDayOfWeek=0,
startTime=0,en‌​dMode=0,endMonth=0,endDay=0,endDayOfWeek=0,endTime=0]

它是否使用GMT?为什么会这样..

编辑:

最终通过使用

,使其工作。

simpleDateFormat.setTimeZone(TimeZone.getTimeZone( "GMT-5")); //GMT-5 is for CDT, I found my server is actually using CDT not CST

仍然不知道为什么使用字符串“CST”不能正常工作...


1
不要使用时区的缩写,始终使用完整名称。EST 可以是东部标准时间,也可以是其他某个时区。 - kosa
这个链接可能会有帮助:https://dev59.com/mkzSa4cB1Zd3GeqPmnKm。 - Raghunandan
1
@Nambari 尝试了“中央标准时间”,仍然得到了 GMT... - Arch1tect
通常我们使用America/New_York来获取东部标准时间,可以查看时区数据库中是否有类似的内容。 - kosa
3
通常应将美国中部标准时间指定为America/Chicago。不要传递GMT-5,否则在从CST转换为CDT时将无法获得正确的调整。 - Matt Johnson-Pint
这应该可以解决你的问题。 - user55926
6个回答

10

从 getTimeZone 的 JavaDoc 中:

Returns a TimeZone corresponding to the given id, or GMT for unknown ids. 

An ID can be an Olson name of the form Area/Location, such as America/Los_Angeles. 
The getAvailableIDs() method returns the supported names. 

尝试使用getAvailableIDs函数?


3
CST 在 TimeZone.getAvailableIDs() 返回的时区列表中。 - Planky

4

您可以使用"CST6CDT"时区,它会在中央夏令时(CDT)切换回中央标准时间(CST)或相反时自动提供正确的时间。


2
以下代码对我很有帮助。
TimeZone tzone = TimeZone.getTimeZone("Singapore");
// set time zone to default
tzone.setDefault(tzone);

2
以下内容似乎对我有用,因为我遇到了类似的问题:
Calendar c = Calendar.getInstance(TimeZone.getTimeZone("America/Chicago"));

1
对于任何日期时间转换,我建议使用JODA日期时间库,它帮助我解决了许多日期时间问题。
您可以使用时区初始化日期,并且很容易在它们之间进行转换。
DateTimeZone zone = DateTimeZone.forID("Europe/London");

或者

DateTimeZone zoneUTC = DateTimeZone.UTC;

来自 JODA DATE TIME API

DateTime(DateTimeZone zone)
Constructs an instance set to the current system millisecond time using ISOChronology in the specified time zone.

0
我发现的一件事是,Java的TimeZone不认识“+09:00”,但它认识“GMT+09:00”和“GMT+0900”。

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