簡體   English   中英

TimeZone.getTimeZone(“CST”)返回GMT

[英]TimeZone.getTimeZone(“CST”) returns GMT

我正在將時間從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”無法正常工作...

來自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?

您可以使用“CST6CDT”時區,當中央夏令時(CDT)切換回CST時,它將自動為您提供正確的時間,反之亦然。

以下代碼對我有所幫助。

TimeZone tzone = TimeZone.getTimeZone("Singapore");
// set time zone to default
tzone.setDefault(tzone);

對於任何日期時間轉換我建議使用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.

在遇到類似問題時,以下似乎對我有用:

Calendar c = Calendar.getInstance(TimeZone.getTimeZone("America/Chicago"));

我發現的一件事是Java的TimeZone不識別“+09:00”,但它確實識別出“GMT + 09:00”和“GMT + 0900”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM