英文:
Java - How do I prevent a LocalDate shifting back one day to MySQL Date?
问题
我在Google上搜索了一下,但没有找到即时的解决方案。
- 数据对象有一个LocalDate字段
- MySQL数据库有一个匹配的DATE列
例如,创建了一个日期:
LocalDate d = LocalDate.of(2020, 1, 3);
它被写入到SQL中:
stmt.setObject(1, d)); // 或者使用Date.valueOf(d)的setDate
在SQL中,它被存储为UTC(我猜是这样),因此由于偏移量(+1),现在是2020-01-02
,并且在获取时也是这样。
(如果DATE列不存储小时,则无法将其恢复到第二天。)
英文:
I googled around but didn't find an immediate solution.
- the data object has a LocalDate field
- the MySQL database has a matching DATE column
Date is created, for example:
LocalDate d = LocalDate.of(2020, 1, 3);
It's written to SQL as:
stmt.setObject(1, d)); // or setDate with Date.valueOf(d)
In SQL it's stored as UTC (I guess) so due to the offset (+1) it's now 2020-01-02
and also fetched as such.
(It obviously can't restore to the next day if DATE column doesn't store the hours.)
答案1
得分: 1
你可以尝试设置一个String
,而不是一个Object
,让数据库将其转换为DATE
。代码大致如下:
LocalDate d = LocalDate.of(2020, 1, 3);
stmt.setString(1, d.format(DateTimeFormatter.ISO_LOCAL_DATE));
这应该可以保持日期值不变(如果能正常工作的话)。在这种情况下,Object
的转换可能会出问题。
英文:
You can try to set a String
instead of an Object
and let the database convert that to a DATE
. This would basically look like
LocalDate d = LocalDate.of(2020, 1, 3);
stmt.setString(1, d.format(DateTimeFormatter.ISO_LOCAL_DATE));
This should keep the date values as they are (if working at all). The Object
conversion could be a problem here.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论