2014-11-14 94 views
1
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.Date; 
import java.util.TimeZone; 


public class DefaultChecks { 
    public static void main(String[] args) { 

     SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); 

     Calendar presentCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); 

     System.out.println("With Cal.."+dateFormatGmt.format(presentCal.getTime())); 

     dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); 

     String currentDateTimeString = dateFormatGmt.format(new Date()); 

     System.out.println("With format.."+currentDateTimeString); 

    } 
} 

OUTPUT:爲什麼將本地時間轉換爲GMT時的差異?

With Cal..2014-11-14T12:50:23.400Z 
With format..2014-11-14T07:20:23.400Z 

回答

1

一個日期是在某個時刻,你的TimeZone(S)是兩種格式調用之間的不同。將其更改爲

SimpleDateFormat dateFormatGmt = new SimpleDateFormat(
      "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); 
    Calendar presentCal = Calendar.getInstance(TimeZone.getTimeZone("GMT")); 
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT")); // <-- here 
    System.out.println("With Cal.." 
      + dateFormatGmt.format(presentCal.getTime())); // <-- you use it 
                  // here. 
    String currentDateTimeString = dateFormatGmt.format(new Date()); 
    System.out.println("With format.." + currentDateTimeString); 

我在這裏得到正確的輸出。

+0

因此,在日曆presentCal = Calendar.getInstance(TimeZone.getTimeZone(「GMT」))中設置時區爲「GMT」;'不會將TimeZone更改爲「GMT」?只有'dateFormatGmt.setTimeZone(TimeZone.getTimeZone(「GMT」));'可以做到這一點? –

+0

@VedPrakash號改變你的本地時區可以做到這一點。日期是時間的表示,表示時間爲自紀元以來的一些毫秒數,它沒有固有的時區(或者說它是GMT)。只有當您將其格式化爲輸出(或解析輸入)纔會影響*顯示的*值。像什麼'System.out.println(0.1 + 0.1 + 0.1);'?計算機並不總是像你天真地期望的那樣行事。 –

相關問題