【发布时间】:2017-06-08 08:18:52
【问题描述】:
基本上,我想设置日期并将其保存到列表中。从我下面的代码:
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"
【问题讨论】:
-
哦,使用 JSR-310 中的
LocalDate(Java 8 内置,也向后移植到 Java 6 和 7)会更容易、更自然。这些天你不应该使用SimpleDateFormat,尤其不应该用于这样的任务。
标签: java simpledateformat date-parsing