设置输入日期并将其添加到列表

Set input date and add it to list

基本上,我想设置日期并将其保存到列表中。来自我的以下代码:

public List<RecordList> createRecord(BigDecimal yr){

    for (int index = 0; index <= 14; index++) {
        RecordList value = new RecordList();
        if(index == 0){
            value.setStartDt(toDate(("01-04-" + yr)));
            value.setEndDt(toDate(("30-04-" + yr)));
        }
        if(index == 1){
            value.setStartDt(toDate(("01-05-" + yr.add(new BigDecimal(1)))));
            value.setEndDt(toDate(("31-05-" + yr.add(new BigDecimal(1)))));
        }
        createRecord.add(newRecordValue);
    return createRecord;
}

private Date toDate(String date) {
    Date newDate = null;
    try {
        newDate = new SimpleDateFormat("dd-MM-YYYY").parse(date);
    }
    catch (ParseException e) {
        e.printStackTrace();
    }
    return newDate;
}

发生的事情是,当我将年份设置为 2017 年时,输出与我设置的不匹配:

"StartDate": "30-12-2017",
 "EndDate": "30-12-2017"

它不会增加到明年,而是减少到:

"StartDate": "30-12-2016",
 "EndDate": "30-12-2016"

大写 Y 是星期年。您必须使用小写字母 y 作为日历年:

newDate = new SimpleDateFormat("dd-MM-yyyy").parse(date);

有关详细信息,请阅读 SimpleDateFormat

的 Javadoc

@Jens的回答是正确的,应该采纳。

我添加了一些建议如何改进错误处理。如您所见,SimpleDateFormat 没有说明您的代码有什么问题。而且我确信这种行为已经导致许多人发布大量有时 "surprising" 行为的解析代码。幸运的是,您只是偶然发现了问题。


Java-8

新的内置库 java.time(自 Java-8 起可用)不会解析但抛出异常

DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MM-YYYY");
LocalDate d = LocalDate.parse("30-12-2017", dtf);

出现以下错误消息:

Exception in thread "main" java.time.format.DateTimeParseException: Text '30-12-2017' could not be parsed: Unable to obtain LocalDate from TemporalAccessor: {MonthOfYear=12, WeekBasedYear[WeekFields[MONDAY,4]]=2017, DayOfMonth=30}...

错误消息中字段 "WeekBasedYear" 的存在应该会告诉您哪里出了问题,因此您可以去文档中查找正确的模式符号。

顺便说一下,Java-6+7 还有一个后向移植 Threeten-BP。我现在还测试了流行的库 Joda-Time:

DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MM-YYYY");
System.out.println(dtf.parseLocalDate("30-12-2017")); // 2017-12-30 (don't use it!)

所以 Java-8 也是对 Joda-Time 的改进,它在你的模式中没有发现任何问题。


我的图书馆Time4J

ChronoFormatter<PlainDate> cf =
    ChronoFormatter.ofDatePattern("dd-MM-YYYY", PatternType.CLDR, Locale.ROOT);
LocalDate d = cf.parse("30-12-2017").toTemporalAccessor(); // not even executed

此处解析器的构造失败并显示以下消息:

java.lang.IllegalArgumentException:
Y as week-based-year requires a week-date-format: dd-MM-YYYY