2016-04-28 41 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时区中的格式用于创建时间字符串,而不是用于解析的格式化程序