我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
我使用的日期格式为:yyyy-mm-dd。
如何将此日期增加一天?
当前回答
自Java 1.5以来,TimeUnit.DAYS.toMillis(1)对我来说看起来更干净。
SimpleDateFormat dateFormat = new SimpleDateFormat( "yyyy-MM-dd" );
Date day = dateFormat.parse(string);
// add the day
Date dayAfter = new Date(day.getTime() + TimeUnit.DAYS.toMillis(1));
其他回答
我认为最快的一个,永远不会被弃用,它是一个深入核心的
let d=new Date();
d.setTime(d.getTime()+86400000);
console.log(d);
只有一行, 只有两个命令。 它工作在日期类型,不使用日历。
我一直认为最好在代码端使用unix时间,并在准备好显示给用户时显示日期。
要打印日期d,我使用
let format1 = new Intl.DateTimeFormat('en', { year: 'numeric', month: 'numeric', month: '2-digit', day: '2-digit'});
let [{ value: month },,{ value: day },,{ value: year }] = format1.formatToParts(d);
它可以设置月、年和日,但可以扩展到小时、分钟和秒,也可以根据国家国旗在标准表示中使用。
使用DateFormat API将字符串转换为日期对象,然后使用Calendar API添加一天。如果您需要特定的代码示例,请告诉我,我可以更新我的答案。
如果您想添加一个时间单位,并且希望其他字段也增加,则可以安全地使用add方法。请看下面的例子:
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance();
cal.set(1970,Calendar.DECEMBER,31);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, 1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
cal.add(Calendar.DATE, -1);
System.out.println(simpleDateFormat1.format(cal.getTime()));
将打印:
1970-12-31
1971-01-01
1970-12-31
更新(2021年5月):这是一个非常过时的老Java的答案。对于Java 8及以上版本,请参见https://stackoverflow.com/a/20906602/314283
与c#相比,Java确实远远落后于八球。这个实用程序方法展示了在Java SE 6中使用Calendar的方法。添加方法(可能是唯一简单的方法)。
public class DateUtil
{
public static Date addDays(Date date, int days)
{
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, days); //minus number would decrement the days
return cal.getTime();
}
}
根据所问的问题,加一天,如下所示:
String sourceDate = "2012-02-29";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = format.parse(sourceDate);
myDate = DateUtil.addDays(myDate, 1);
Java 8添加了一个新的API来处理日期和时间。
在Java 8中,你可以使用以下代码行:
// parse date from yyyy-mm-dd pattern
LocalDate januaryFirst = LocalDate.parse("2014-01-01");
// add one day
LocalDate januarySecond = januaryFirst.plusDays(1);