new*_*bie 0 java date-parsing simpledateformat
基本上,我想设置日期并将其保存到列表中.从下面的代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
会发生什么,当我将年份设置为2017年时,输出与我设置的不匹配:
"StartDate": "30-12-2017",
"EndDate": "30-12-2017"
Run Code Online (Sandbox Code Playgroud)
并且它不会增加到明年,而是减少到:
"StartDate": "30-12-2016",
"EndDate": "30-12-2016"
Run Code Online (Sandbox Code Playgroud)
大写Y是周年.您必须在日历年使用小写y:
newDate = new SimpleDateFormat("dd-MM-yyyy").parse(date);
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请阅读SimpleDateFormat的Javadoc