我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
当前回答
构造一个Calendar对象并调用add(Calendar。目前为止,1);
其他回答
只需在字符串中传递日期和接下来的天数
private String getNextDate(String givenDate,int noOfDays) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
String nextDaysDate = null;
try {
cal.setTime(dateFormat.parse(givenDate));
cal.add(Calendar.DATE, noOfDays);
nextDaysDate = dateFormat.format(cal.getTime());
} catch (ParseException ex) {
Logger.getLogger(GR_TravelRepublic.class.getName()).log(Level.SEVERE, null, ex);
}finally{
dateFormat = null;
cal = null;
}
return nextDaysDate;
}
Date newDate = new Date();
newDate.setDate(newDate.getDate()+1);
System.out.println(newDate);
如果你使用的是Java 8, Java .time. localdate和Java .time.format. datetimeformatter可以让这个工作变得非常简单。
public String nextDate(String date){
LocalDate parsedDate = LocalDate.parse(date);
LocalDate addedDate = parsedDate.plusDays(1);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd");
return addedDate.format(formatter);
}
构造一个Calendar对象并调用add(Calendar。目前为止,1);
请注意这一行增加了24小时:
d1.getTime() + 1 * 24 * 60 * 60 * 1000
但是这条线增加了一天
cal.add( Calendar.DATE, 1 );
在夏令时改变的日子里(25或23小时),你会得到不同的结果!