且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在日期中添加一天?

更新时间:2023-01-29 19:50:59

给定一个 Date dt 你有几种可能性:

Given a Date dt you have several possibilities:

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

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

解决方案 2:您应该认真考虑使用 Joda-时间库,由于Date类的种种缺点.使用 Joda-Time,您可以执行以下操作:

Solution 2: You should seriously consider using the Joda-Time library, because of the various shortcomings of the Date class. With Joda-Time you can do the following:

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

解决方案 3:通过 Java 8,您还可以使用新的 JSR 310 API(受 Joda-Time 启发):

Solution 3: With Java 8 you can also use the new JSR 310 API (which is inspired by Joda-Time):

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