Java 中无法解析的日期:基本日历实例解析 SimpleDateFormat 的问题

Unparsable Date in Java: Basic Calendar instance parse issues with SimpleDateFormat

我正在尝试将当前时间和日期解析为这种简单的日期格式。

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy-kk:mm");
Date datetoday = sdf.parse(Calendar.getInstance().getTime().toString());

不过,我明白了。

java.text.ParseException:无法解析的日期:"Tue May 17 15:28:36 CDT 2016"

我仍然能够解析像 5/5/1991-12:00 这样的字符串,但是当给定一个日历实例时,它就会崩溃。我真的应该从一开始就使用JodaTime

我怎样才能将当前时间直接输入到 SimpleDateFormat 中?据我了解,SimpleDateFormat 将接受字符串并将其转换为日期,一旦它能够解析它。解析将看到 Tue 将进入 SDF 中的 ddd 区域,如果我将 May 进入 MMM有一个简单的日期格式。我不。我有MM,所以它炸了。我可以在输入中做一个 M/d/yyyy,所以我最终给它 M,同时要求 MM,这仍然有效。

我应该放弃所有内容并使用 JodaTime 还是缺少一两行?

这是获取表示为 Java 日期对象的当前日期的方法:

Date date = new Date();

这是您获取当前日期作为格式化字符串的方式:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy-kk:mm");
String formattedDateString = sdf.format(new Date());

然后您可以进一步将其解析回日期:

Date date = sdf.parse(formattedDateString);

但是这样做没有意义,因为您在调用 .format(...) 时已经有了日期,只是在您使用的情况下

Calendar.getInstance().getTime()

通常会给出与

相同的结果
new Date()

如果要将字符串解析为 Date,则该字符串需要与 SimpleDateFormat 构造函数中指定的格式相匹配。您正在使用的 Date 的 toString() 方法 returns 特定格式的字符串与示例中的格式不匹配,这就是您收到 ParseException 错误的原因。

字符串 != 日期时间

不要将日期时间对象与表示其值的字符串混淆。

您应该尽可能多地使用对象。生成一个仅用于呈现给用户的字符串。使用字符串与其他软件交换数据时,只能使用 ISO 8601 格式。

java.time

问题和接受的答案都使用麻烦的旧旧日期时间 类,现在被 java.time 类.

取代

您的输入格式不标准且含糊不清。末尾的 -12:00 是时区还是时间?我猜一天中的某个时间。该猜测意味着输入缺少任何与 UTC 或时区的偏移量指示。所以我们解析为一个 LocalDateTime 对象。

String input = "5/5/1991-12:00"
DateTimeFormatter f = DateTimeFormatter.ofPattern( "M/d/uuuu-HH:mm" );
LocalDateTime ldt = LocalDateTime.format( input , f );

ldt.toString(): 1991-05-05T12:00

一个 LocalDateTime 对象故意缺少任何 offset-from-UTC 或时区。这意味着它 而不是 代表时间轴上的一个时刻,只是对可能时刻的粗略了解。您必须指定一个时区才能赋予它意义。

如果您的建议的上下文表明此输入应该在 UTC 中,请应用常量 ZoneOffset.UTC 以获得 OffsetDateTime.

OffsetDateTime odt = ldt.atOffset ( ZoneOffset.UTC );

odt.toString(): 1991-05-05T12:00Z

标准 ISO 8601 字符串末尾的 ZZuluUTC.

的缩写

另一方面,如果上下文指示特定时区,则应用 ZoneId 以获得 ZonedDateTime。您的示例输入字符串适用于哪个时区?您是指新西兰奥克兰的中午、法国巴黎的中午还是加利福尼亚州蒙特利尔魁北克的中午?

ZoneId z = ZoneId.of ( "America/Montreal" );
ZonedDateTime zdt = ldt.atZone ( z );

zdt.toString(): 1991-05-05T12:00-04:00[America/Montreal]


关于java.time

java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

Joda-Time project, now in maintenance mode, advises migration to the java.time 类.

要了解更多信息,请参阅 Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310

您可以直接与数据库交换 java.time 对象。使用 JDBC driver compliant with JDBC 4.2 或更高版本。不需要字符串,不需要 java.sql.* 类.

在哪里获取java.time类?

ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.