gpt4 book ai didi

java - MySQL 中保存的日期无效

转载 作者:行者123 更新时间:2023-11-29 04:42:10 25 4
gpt4 key购买 nike

请看下面的代码

SimpleDateFormat format = new SimpleDateFormat("dd-mm-yyyy");
Date parse = format.parse("05-10-2014");
java.sql.Date sqlDate = new java.sql.Date(parse.getTime());

输出“应该是”05-10-2014,但我得到的输出是 2014-01-05。这里有什么问题?

即使我将 sqlDate 保存在数据库中,它仍被保存为 2014-01-05

更新

我将 dd-mm-yyyy 更改为 dd-MM-yyyy。现在,mysql将其保存为2014-05-10

最佳答案

如果您担心日期的格式,java.sql.Date toString() 方法,当您println 时调用的方法 它,always将日期格式化为 yyyy-mm-dd

如果您想以更可控的方式格式化日期,可以在输出时使用 DateFormat

但是,这里的真正问题(错误数据)是您使用的是小写 m,它是“小时中的分钟”,而不是“年中的月”。查看SimpleDateFormat详情页:

Letter  Date or Time Component  Presentation  Examples
------ ---------------------- ------------ --------
M Month in year Month July; Jul; 07
m Minute in hour Number 30

在上面的第二个链接中,pards() 的描述有这个小片段:

This parsing operation uses the calendar to produce a Date. All of the calendar's date-time fields are cleared before parsing, and the calendar's default values of the date-time fields are used for any missing date-time information.

由于 Calendar 的默认值是 1970 年 1 月 1 日,而您只设置了日期、分钟和年份,因此您将以 2014 年 1 月 5 日(午夜过后十分钟)结束), 假设 UTC。

将格式字符串更改为 "dd-MM-yyyy" 应该可以解决眼前的问题。

关于java - MySQL 中保存的日期无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26200178/

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