Java – 如何防止 LocalDate 在存储到 MySQL 日期时向前偏移一天?

huangapple go评论72阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年10月8日 21:02:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/64263132.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定