DateTimeFormatter无法解析日期字符串,但SimpleDateFormat能够

问题描述 投票:0回答:1

我无法使用LocalDate解析方法来解析此示例日期字符串-表示“ 2015年1月3日”的“ 312015”。可以请人帮忙。

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

public class TestDOB {

    public static void main(String[] args) throws ParseException {
        // TODO Auto-generated method stub

        String dateOfBirth = "312015";
        SimpleDateFormat sdf = new SimpleDateFormat("dMyyyy");
        System.out.println(sdf.parse(dateOfBirth)); 
        // The above outputs Sat Jan 03 00:00:00 CST 2015

        DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dMyyyy").withLocale(Locale.getDefault());
        LocalDate dateTime = LocalDate.parse(dateOfBirth, dateFormatter);

        // The above parsing statement with LocalDate parse method runs into below error - 


    }

}

Error on console- 

Exception in thread "main" java.time.format.DateTimeParseException: Text '312015' could not be parsed at index 6
    at java.time.format.DateTimeFormatter.parseResolved0(Unknown Source)
    at java.time.format.DateTimeFormatter.parse(Unknown Source)
    at java.time.LocalDate.parse(Unknown Source)
    at TestDOB.main(TestDOB.java:30)
java datetime-format localdate
1个回答
0
投票

我很惊讶地发现这是可能的(对我来说这没有多大意义。)>

    DateTimeFormatter dateFormatter = new DateTimeFormatterBuilder()
            .appendValue(ChronoField.DAY_OF_MONTH, 1)
            .appendValue(ChronoField.MONTH_OF_YEAR, 1)
            .appendValue(ChronoField.YEAR, 4)
            .toFormatter();

    String dateOfBirth = "312015";
    LocalDate dateTime = LocalDate.parse(dateOfBirth, dateFormatter);
    System.out.println(dateTime);

此代码段的输出是:

2015-01-03

但是,它有一些局限性,我认为这很严重:它只能解析1月至9月(非10月至12月)的月份1–9天(而非10–31)内的日期一个月中的某天和每个月中的每个月只有1位数字。

您可以通过从第一次调用到1省略第二个参数appendValue()来摆脱每月的日期]的限制。类似的技巧将not

在该月份有效,因此该年度的最后一个季度已无法使用。
© www.soinside.com 2019 - 2024. All rights reserved.