2014-11-14 197 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);'?计算机并不总是像你天真地期望的那样行事。 –

相关问题