GMT和CST的轉換


    GMT時間是格林尼治標准時間。CST時間是指包含中國。美國。巴西,澳大利亞四個時區的時間。

 在javascript中默認CST是指美國中部時間,倘若在javascript中GMT轉換CST則兩者相差14個小時。在java后台中默認的是北京時間,GMT轉換成CST則相差8個小時。各個地方用CST時間得到的可能會有所不同。所以為了避免編程錯誤,一般使用GMT時間。

下面是從其它地方找到的三種轉換方式。

  1.  第一種方式:
    Date date = new Date(); 
    date.toGMTString();
    因此方法在高版本號的JDK中已經失效,不推薦使用。

  2.  另外一種方式
    DateFormat cstFormat = new SimpleDateFormat(); 
    DateFormat gmtFormat = new SimpleDateFormat(); 
    TimeZone gmtTime = TimeZone.getTimeZone("GMT"); 
    TimeZone cstTime = TimeZone.getTimeZone("CST");       
    cstFormat.setTimeZone(gmtTime); 
    gmtFormat.setTimeZone(cstTime); 
    System.out.println("GMT Time: " + cstFormat.format(date)); 
    System.out.println("CST Time: " + gmtFormat.format(date)); 
    得到的格式非常單調。僅僅有年月日+上下午+時分。

    感覺不太好用,不推薦使用

  3. 第三種方式
    public Date getCST(String strGMT) throws ParseException { 
       DateFormat df = new SimpleDateFormat("EEE, d-MMM-yyyy HH:mm:ss z", Locale.ENGLISH); 
       return df.parse(strGMT); 
    } 
    
    public String getGMT(Date dateCST) { 
       DateFormat df = new SimpleDateFormat("EEE, d-MMM-yyyy HH:mm:ss z", Locale.ENGLISH); 
       df.setTimeZone(TimeZone.getTimeZone("GMT")); // modify Time Zone. 
       return(df.format(dateCST)); 
    } 
    一般我們的web請求的請求頭中的Date格式類似於:Thu, 02 Jul 2015 05:49:30 GMT ,能夠對應的把上面的格式調整為:
    DateFormat df = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z", Locale.ENGLISH);
    這樣的方式能夠靈活控制時間的格式,信息量較全,推薦使用。
  4. 以下是三種方式測試的結果:






免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM