DateFormat的parse()与SimpleDateFormat之间的区别

Jig*_*aik 6 java java-8

我正在尝试使用LocalDateTime.parse该方法解析日期,但是我遇到了以下错误。如果我使用SimpleDateFormat简单的日期格式对象,则日期字符串将被解析。

有没有人遇到这个问题!从DateFormat和解析之间有什么区别LocalDateTime

package com.example.demo;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class App {

    public static final String DATE_TIME_PATTERN = "dd-MM-yyyy hh:mm:ss.SSS";

    public static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat(DATE_TIME_PATTERN);

    public static final String SEPERATOR = ",";

    public static void main(String[] args) {
        try {
            Date date = DATE_TIME_FORMAT.parse("12-03-2019 10:28:50.013");
            System.out.println("date : {} " + date);

            LocalDateTime startTimestamp = LocalDateTime.parse("12-03-2019 10:28:50.013", DateTimeFormatter.ofPattern(DATE_TIME_PATTERN)).plusNanos(1000000);
            System.out.println("startTimestamp : {} " + startTimestamp);
        } catch(Exception e) {
            e.printStackTrace();
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

输出值

date : {} Tue Mar 12 10:28:50 SGT 2019
java.time.format.DateTimeParseException: Text '12-03-2019 10:28:50.013' could not be parsed: Unable to obtain LocalDateTime from TemporalAccessor: {NanoOfSecond=13000000, HourOfAmPm=10, MicroOfSecond=13000, SecondOfMinute=50, MilliOfSecond=13, MinuteOfHour=28},ISO resolved to 2019-03-12 of type java.time.format.Parsed
    at java.time.format.DateTimeFormatter.createError(DateTimeFormatter.java:1920)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1855)
    at java.time.LocalDateTime.parse(LocalDateTime.java:492)
    at com.example.demo.App.main(App.java:21)
Caused by: java.time.DateTimeException: Unable to obtain LocalDateTime from TemporalAccessor: {NanoOfSecond=13000000, HourOfAmPm=10, MicroOfSecond=13000, SecondOfMinute=50, MilliOfSecond=13, MinuteOfHour=28},ISO resolved to 2019-03-12 of type java.time.format.Parsed
    at java.time.LocalDateTime.from(LocalDateTime.java:461)
    at java.time.format.Parsed.query(Parsed.java:226)
    at java.time.format.DateTimeFormatter.parse(DateTimeFormatter.java:1851)
    ... 2 more
Caused by: java.time.DateTimeException: Unable to obtain LocalTime from TemporalAccessor: {NanoOfSecond=13000000, HourOfAmPm=10, MicroOfSecond=13000, SecondOfMinute=50, MilliOfSecond=13, MinuteOfHour=28},ISO resolved to 2019-03-12 of type java.time.format.Parsed
    at java.time.LocalTime.from(LocalTime.java:409)
    at java.time.LocalDateTime.from(LocalDateTime.java:457)
    ... 4 more
Run Code Online (Sandbox Code Playgroud)

Ful*_*Guy 4

您正在使用时钟小时-上午-下午 (1-12)h表示您的模式中的小时,而不是一天中的小时 (0-23) ,因此H它需要上午/的附加信息下午。

在此输入图像描述

a因此,理想情况下,必须在要与am-pm-of-day一起解析的日期字符串中提及 AM/PM,该日期字符串也需要添加到DATE_TIME_PATTERN字符串中。

public static final String DATE_TIME_PATTERN = "dd-MM-yyyy hh:mm:ss.SSS a";

public static final DateFormat DATE_TIME_FORMAT = new SimpleDateFormat(DATE_TIME_PATTERN);

  public static final String SEPERATOR = ",";

    public static void main(String[] args) {
        try {
            Date date = DATE_TIME_FORMAT.parse("12-03-2019 10:28:50.013 AM");
            System.out.println("date : {} " + date);

            LocalDateTime startTimestamp = LocalDateTime.parse("12-03-2019 10:28:50.013 AM", DateTimeFormatter.ofPattern(DATE_TIME_PATTERN)).plusNanos(1000000);
            System.out.println("startTimestamp : {} " + startTimestamp);
        } catch(Exception e) {
            e.printStackTrace();
        }

    }
Run Code Online (Sandbox Code Playgroud)

输出:

date : {} Tue Mar 12 10:28:50 IST 2019
startTimestamp : {} 2019-03-12T10:28:50.014
Run Code Online (Sandbox Code Playgroud)

我们可以看到,如果没有正确的格式,SimpleDateFormatLocalDateTime在解析无效日期字符串时会更加严格。在您的情况下,由于缺少所需的 AM/PM 信息,因此LocalTime返回的是TemporalAccessornull因此您将得到Unable to obtain LocalTime from TemporalAccessor.

不知道为什么SimpleDateFormat有效,setLenient(boolean lenient)如果您经过的时间大于模式中12未提及的时间,并且日期字符串中的 AM/PM将被抛出,则会调用一个方法。ajava.text.ParseException: Unparseable date:

但由于在您的情况下,您正在通过小时,因为10这小于12,因此默认情况下它被解释为上午

这是 SimpleDateFormat 类中进行此检查的代码:

case PATTERN_HOUR1: // 'h' 1-based.  eg, 11PM + 1 hour =>> 12 AM
     if (!isLenient()) {
         // Validate the hour value in non-lenient
         if (value < 1 || value > 12) {
             break parsing;
         }
     }
     // [We computed 'value' above.]
     if (value == calendar.getLeastMaximum(Calendar.HOUR) + 1) {
         value = 0;
     }
     calb.set(Calendar.HOUR, value);
     return pos.index;
Run Code Online (Sandbox Code Playgroud)