【发布时间】:2021-04-16 17:12:52
【问题描述】:
我有一个大问题,我必须以正确的方式格式化日期。我的解决方案建议如下:
...
//Read: 1935-05-12 00:00:00.0
Date dateOfBirth= (Date) arrayOfObject[3];
//Pattern: dd-MM-yyyy hh:mm:ss
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
//12-05-1935 12:00:00 (for me it's perfect but I need Date and no String)
String strDate = dateFormat.format(dateOfBirth);
//Read: Sun May 12 00:00:00 CET 1935
dateOfBirth= dateFormat.parse(strDate);
//Read: Sun May 12 00:00:00 CET 1935
rep.setDateOfBirth(dateOfBirth);
...
我需要像 strDate 这样的格式,因为我需要这种格式的数据库,但我需要一个日期而不是字符串,我不知道怎么做我以正确的方式格式化我的日期字符串。
【问题讨论】:
-
我不确定你在问什么。你已经有一个
Date。Date是一个时刻。日期的表示可以是字符串。 -
我建议你不要使用
SimpleDateFormat和Date。这些类设计不佳且早已过时,尤其是前者,尤其是出了名的麻烦。而是使用来自java.time, the modern Java date and time API 的LocalDateTime和DateTimeFormatter。 -
这能回答你的问题吗? display Java.util.Date in a specific format。 this?
-
自从你得到
1935-05-12 00:00:00.0,看起来你真的从你的数组中得到了一个java.sql.Timestamp对象。这是另一个设计不佳且早已过时的类,是Date的子类,并且是在它之上的真正hack。 -
还请解释一下,当原始对象中的时间是 00:00:00.0 时,12:00:00 怎么可能是完美的?
标签: java date simpledateformat date-format