Simpledateformat 解析减法而不是加法
Simpledateformat parse subtracts instead of adding
我正在尝试将我获得的时间(CEST/CET)更改为 GMT 以将其存储在我的数据库中。但是当我将 CEST 中的日期解析为 GMT 时,它没有减去 2,而是增加了 2 小时!
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);
谁能解释一下为什么?我试过将我的本地时区设置为不同的时区,但它总是以另一种方式工作,减去而不是加,反之亦然。
您再次将日期解析为 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);
基本上,您必须在用于创建时间字符串的时间格式中设置 GMT 时区,而不是用于解析的格式化程序
我正在尝试将我获得的时间(CEST/CET)更改为 GMT 以将其存储在我的数据库中。但是当我将 CEST 中的日期解析为 GMT 时,它没有减去 2,而是增加了 2 小时!
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);
谁能解释一下为什么?我试过将我的本地时区设置为不同的时区,但它总是以另一种方式工作,减去而不是加,反之亦然。
您再次将日期解析为 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);
基本上,您必须在用于创建时间字符串的时间格式中设置 GMT 时区,而不是用于解析的格式化程序