gpt4 book ai didi

java - Simpledateformat 解析减法而不是加法

转载 作者:行者123 更新时间:2023-12-02 03:40:08 25 4
gpt4 key购买 nike

我正在尝试将我获得的时间(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);

基本上,您必须在用于创建时间字符串的 timeFormat 中设置 GMT 时区,而不是用于解析的格式化程序

关于java - Simpledateformat 解析减法而不是加法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36920197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com