如何在日期中添加一天?

2022-08-31 05:31:44

我想在特定日期添加一天。我该怎么做?

Date dt = new Date();

现在我想在这个日期上加上一天。


答案 1

给定您有几种可能性:Date dt

解决方案 1:您可以使用该类:Calendar

Date dt = new Date();
Calendar c = Calendar.getInstance(); 
c.setTime(dt); 
c.add(Calendar.DATE, 1);
dt = c.getTime();

解决方案 2:你应该认真考虑使用Joda-Time库,因为该类有各种缺点。使用Joda-Time,您可以执行以下操作:Date

Date dt = new Date();
DateTime dtOrg = new DateTime(dt);
DateTime dtPlusOne = dtOrg.plusDays(1);

解决方案 3:Java 8中,您还可以使用新的JSR 310 API(其灵感来自Joda-Time):

Date dt = new Date();
LocalDateTime.from(dt.toInstant()).plusDays(1);

答案 2
Date today = new Date();
Date tomorrow = new Date(today.getTime() + (1000 * 60 * 60 * 24));

Date 具有一个使用自 UNIX 纪元以来的毫秒的构造函数。getTime()-方法为您提供了该值。因此,将毫秒添加到一天中,就可以了。如果你想定期进行这样的操作,我建议为值定义常量。

重要提示:并非所有情况下都是正确的。阅读下面的警告注释。