2010-01-13 22 views
3

正在嘗試轉換日期是在本地時區爲GMT,我做了一些這樣的事轉換本地時區以GMT的在Java

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 
     sdf.setTimeZone(TimeZone.getTimeZone("GMT")); 
     String gmtStrDate = sdf.format(Calendar.getInstance().getTime()); 

     System.out.println("GMT 1"+gmtStrDate); 

     Date gmtDate = sdf.parse(gmtStrDate); 

     System.out.println("GMT 2"+gmtDate); 

我得到GMT 1 O/P在GMT TZ但格林尼治標準時間2 o/p再次改變爲當地時區...任何可以告訴我爲什麼?

得到GMT 2 O/P在GMT我沒有這樣的:

日曆日曆= Calendar.getInstance(TimeZone.getTimeZone( 「GMT」)); calendar.setTime(gmtDate);

 System.out.println("GMT 3 = "+calendar.getTime()); 

但仍北京時間30/P我得到當地TZ。請在此建議。

回答

2

後 '解析' 你打印前必須重新格式化,例如:

System.out.println("GMT 2"+sdf.format(gmtDate)); 

編輯: 原因是你的gmtStrDate不存儲任何區信息

+0

你好南大, 感謝您的更新,但在這裏,如果我再次格式化我將它作爲字符串權利,但我想在日期,所以我想解析它。 如果你對此有任何意見,請讓我知道。 – Sreekar

+0

嗨...如果這是你的意圖,你會得到正確的結果。儘管如此,您必須正確打印它(以GMT格式)。 System.out.println(「GMT 3 =」+ sdf.format(calendar.getTime())); calendar.getTime()包含所需的數據。 – nanda

13
import java.util.*; 
import java.text.*; 
public class CurrentTimeToGMT{ 
    public static void main(String args[]){ 
    Date date = new Date(); 
    DateFormat gmtFormat = new SimpleDateFormat(); 
    TimeZone gmtTime = TimeZone.getTimeZone("GMT"); 
    gmtFormat.setTimeZone(gmtTime); 
    System.out.println("Current Time: "+date); 
    System.out.println("GMT Time: " + gmtFormat.format(date)); 

    } 
} 

輸出

 
Current Time: Wed Mar 10 11:21:18 IST 2010 

GMT Time: 3/10/10 5:51 AM