2016-04-28 78 views
0

我試圖改變我得到(在CEST/CET中)到GMT的時間以將其存儲在我的數據庫中。但是當我將CEST中的日期解析爲GMT時,而不是減去2,它會增加2小時!Simpledateformat分析減去而不是添加

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); //My locale is CEST 
Date dateOfBooking = formatter.parse(bookedDate + " " + bookedDateTime); //Here the time is 10:09 

formatter.setTimeZone(TimeZone.getTimeZone("GMT")); // Timezone I need to store the date in 
dateOfBooking = formatter.parse(bookedDate + " " + bookedDateTime); // Here the time is 12:09 
DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); 
bookedDateTime = timeFormat.format(dateOfBooking); 

任何人都可以解釋爲什麼嗎?我嘗試將我的本地時區設置爲不同的時區,並且它始終以另一種方式工作,減去而不是添加,反之亦然。

+1

「CEST」不是區域設置,它是時區。區域設置確定用於翻譯星期幾的人類語言以及逗號與期間之間的文化規範。但區域設置與時區完全分開且無關。另一個問題:'CEST'不是一個真正的時區。 [適當時區](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)是一個大陸/地區,如「歐洲/巴黎」。 –

回答

2

您正在將日期再次解析爲GMT。 (其中,當作爲CEST,或您所在地區時區印刷,將增加+ 2小時)

你真正想要的是打印出來的已經被解析日期爲GMT:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()); //My locale is CEST 
Date dateOfBooking = formatter.parse(bookedDate + " " + bookedDateTime); //Here the time is 10:09 

DateFormat timeFormat = new SimpleDateFormat("HH:mm:ss"); 
timeFormat.setTimeZone(TimeZone.getTimeZone("GMT")); 
bookedDateTime = timeFormat.format(dateOfBooking); 
System.out.println(bookedDateTime); 

Basicly你必須設置GMT時區中的格式用於創建時間字符串,而不是用於解析的格式化程序