【发布时间】:2021-08-23 18:51:32
【问题描述】:
我使用ZonedDateTime 来获取当前日期时间。因为我不想要它,所以我将它设为uuuu-MM-dd 的格式,它给了我一个字符串2021-08-23
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.systemDefault());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "uuuu-MM-dd" );
String date_string = zdt.format(formatter);
System.out.println(date_string);//2021-08-23
现在我怎样才能将此字符串2021-08-23 转换为java.util.Date?我希望日期看起来完全像字符串......
这是我尝试过的,但它不会让我得到看起来像字符串的日期
SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter1.parse(date_string);
将以这种格式给我日期:Mon Aug 23 00:00:00 EEST 2021... 我该怎么做
将我的字符串转换为日期并保持日期看起来像字符串?
【问题讨论】:
-
为什么需要
java.util.Date?顺便说一句,该类没有格式。您看到的是应用默认格式化程序的结果。您应该使用自己的格式化程序和String s = formatter1.format(date) -
如何使用另一个日期类来做到这一点?
-
仍然不知道为什么需要
util.Date -
可以将
ZonedDateTime转换为Instant,它具有toDate()方法。然而,你说你想要一个Date,但你没有解释你为什么想要这个。对我来说,这看起来像是一个 XY 问题。 -
我建议您既不要使用
SimpleDateFormat,也不要使用Date。这些类设计不良且过时,尤其是前者,尤其是出了名的麻烦。而是使用LocalDate和可能来自java.time, the modern Java date and time API 的其他类。