我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
当前回答
只需在字符串中传递日期和接下来的天数
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;
}
其他回答
startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender
请注意这一行增加了24小时:
d1.getTime() + 1 * 24 * 60 * 60 * 1000
但是这条线增加了一天
cal.add( Calendar.DATE, 1 );
在夏令时改变的日子里(25或23小时),你会得到不同的结果!
构造一个Calendar对象并调用add(Calendar。目前为止,1);
如果您正在使用Java 8,那么就像这样做。
LocalDate sourceDate = LocalDate.of(2017, Month.MAY, 27); // Source Date
LocalDate destDate = sourceDate.plusDays(1); // Adding a day to source date.
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); // Setting date format
String destDate = destDate.format(formatter)); // End date
如果您想使用SimpleDateFormat,那么就像这样做。
String sourceDate = "2017-05-27"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calendar = Calendar.getInstance();
calendar.setTime(sdf.parse(sourceDate)); // parsed date and setting to calendar
calendar.add(Calendar.DATE, 1); // number of days to add
String destDate = sdf.format(calendar.getTime()); // End date
Date newDate = new Date();
newDate.setDate(newDate.getDate()+1);
System.out.println(newDate);