2013-04-23 22 views
0

我有一個包含日期和時間信息的Java Date對象,例如2010-11-11T09:30:47。我想編寫一個方法將這個Date對象轉換爲下面的格式。 「YYYY-MM-dd'T'HH:MM:ss.SSS'Z」原爲了得到格式的日期時間,我給

我寫下面的代碼

private Calender getValue(Date dateObject) { 
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); 
    formatter.setTimeZone(TimeZone.getTimeZone("GMT")); 

    String timestamp = formatter.format(dateObject); 

    System.out.println("Created GMT cal with date [" + timestamp + "]"); 

    } 

當我運行程序時,它是印刷

創建GMT CAL與日期[2010-11-11T04:00:47.000Z]

我給什麼是 「2010-11-11T09:30:47」,我的時間是9點30分四十七秒。它打印的是「04:00:47」。

爲什麼時間在改變9.30到4.00。?

什麼我需要做的,因爲我給得到相同的時間。像2010-11-11T09:30:47.000Z

非常感謝。

+0

什麼是你輸入的時間戳?你確定最初的'2010-11-11T09:30:47'是GMT嗎?在格式化之前,您是否嘗試過在創建Date對象之前嘗試過? – Quetzalcoatl 2013-04-23 09:31:26

+0

看起來你可能不得不使用偏移量來使用時區。 – Frankline 2013-04-23 09:37:40

回答

1

你只需要刪除以下行

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

因爲你設置時區是GMT,而你的時區爲GMT + 5.30。這就是將時間設置爲9.30時的原因,您將獲得9.30 - 5.30 = 4.00

你可以使用下面的代碼:

private void getValue(Date dateObject) 
{ 
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); 
    String timestamp = formatter.format(dateObject); 
    System.out.println("Created GMT cal with date [" + timestamp + "]"); 
} 
+0

非常感謝您的回覆。我需要「GMT」中的時區。我嘗試了以下代碼。日曆日曆= Calendar.getInstance(TimeZone.getTimeZone(「GMT」)); calendar .setTime(source); calendar.add(Calendar.HOUR,5); calendar.add(Calendar.MINUTE,30);除了2010-11-11T24:00:00它正在打印2010-11-12T24:00:00.000Z之外的所有值。我需要以格式輸入。 – user2299225 2013-04-23 10:11:25

1

你的日期可能有時間9時30分47秒在時區。但是您將日期格式配置爲GMT時區。因此它顯示了GMT時區內的時間。

如果你使用其他日期格式解析輸入字符串,並得到一個Date對象,確保這oter日期格式也使用GMT時區。

爲了得到更多的幫助,我們展示瞭如何創建傳遞給你的方法Date對象。

1

刪除formatter.setTimeZone(TimeZone.getTimeZone( 「GMT」));

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"); 
    String timestamp = formatter.format(new Date()); 
    System.out.println("Created GMT cal with date [" + timestamp + "]");