我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
当前回答
在Java 8中简单的方法是:
Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))
其他回答
请注意这一行增加了24小时:
d1.getTime() + 1 * 24 * 60 * 60 * 1000
但是这条线增加了一天
cal.add( Calendar.DATE, 1 );
在夏令时改变的日子里(25或23小时),你会得到不同的结果!
像这样的东西应该可以达到目的:
String dt = "2008-01-01"; // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime()); // dt is now the new date
java.time
在Java 8及以后的版本中,Java。时间包让这个过程变得很自动。(教程)
假设字符串输入和输出:
import java.time.LocalDate;
public class DateIncrementer {
static public String addOneDay(String date) {
return LocalDate.parse(date).plusDays(1).toString();
}
}
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );
你可以使用"org.apache.commons.lang3.time"中的这个包:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date myNewDate = DateUtils.addDays(myDate, 4);
Date yesterday = DateUtils.addDays(myDate, -1);
String formatedDate = sdf.format(myNewDate);