如何在Java中将日期增加一天?

How can I increment a date by one day in Java?

我正在使用以下格式的日期:yyyy-mm-dd

如何将这一日期增加一天?


这样的事情应该可以解决问题:

1
2
3
4
5
6
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


与C#相比,Java确实确实落后于8球。该实用程序方法显示了使用Calendar.add方法在Java SE 6中执行操作的方法(可能是唯一简便的方法)。

1
2
3
4
5
6
7
8
9
10
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();
    }
}

要添加一天,请根据提出的问题按以下方式致电:

1
2
3
4
String sourceDate ="2012-02-29";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date myDate = format.parse(sourceDate);
myDate = DateUtil.addDays(myDate, 1);


java.time

在Java 8和更高版本上,java.time包使此过程几乎是自动的。 (教程)

假设String输入和输出:

1
2
3
4
5
6
7
import java.time.LocalDate;

public class DateIncrementer {
  static public String addOneDay(String date) {
    return LocalDate.parse(date).plusDays(1).toString();
  }
}


我更喜欢使用Apache的DateUtils。检查此http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/time/DateUtils.html。它非常方便,尤其是当您必须在项目中的多个位置使用它并且不想为此编写一个线性方法时。

API说:

addDays(Date date, int amount) : Adds a number of days to a date returning a new object.

请注意,它将返回一个新的Date对象,并且不会更改前一个对象本身。


1
2
3
4
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd" );
Calendar cal = Calendar.getInstance();
cal.setTime( dateFormat.parse( inputString ) );
cal.add( Calendar.DATE, 1 );

构造一个Calendar对象,并使用方法add(Calendar.DATE,1);


看看Joda-Time(https://www.joda.org/joda-time/)。

1
2
3
4
5
DateTimeFormatter parser = ISODateTimeFormat.date();

DateTime date = parser.parseDateTime(dateString);

String nextDay = parser.print(date.plusDays(1));


Java 8添加了用于处理日期和时间的新API。

使用Java 8,您可以使用以下代码行:

1
2
3
4
5
// parse date from yyyy-mm-dd pattern
LocalDate januaryFirst = LocalDate.parse("2014-01-01");

// add one day
LocalDate januarySecond = januaryFirst.plusDays(1);


请注意,此行会增加24小时:

1
d1.getTime() + 1 * 24 * 60 * 60 * 1000

但是这条线增加了一天

1
cal.add( Calendar.DATE, 1 );

在夏令时更改的日期(25或23小时)内,您将获得不同的结果!


您可以使用Simple java.util lib

1
2
3
4
Calendar cal = Calendar.getInstance();
cal.setTime(yourDate);
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();


1
2
3
4
5
6
Date today = new Date();              
SimpleDateFormat formattedDate = new SimpleDateFormat("yyyyMMdd");            
Calendar c = Calendar.getInstance();        
c.add(Calendar.DATE, 1);  // number of days to add      
String tomorrow = (String)(formattedDate.format(c.getTime()));
System.out.println("Tomorrows date is" + tomorrow);

这将给出明天的日期。可以将c.add(...)参数从1更改为另一个数字以适当地增加。


如果您使用的是Java 8,请按照以下步骤进行操作。

1
2
3
4
5
6
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,请按照以下步骤进行操作。

1
2
3
4
5
6
7
8
9
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


1
2
long timeadj = 24*60*60*1000;
Date newDate = new Date (oldDate.getTime ()+timeadj);

这花费了从oldDate到新纪元以来的毫秒数,并增加了1天的毫秒数,然后使用Date()公共构造函数使用新值创建日期。此方法使您可以添加1天或任意数量的小时/分钟,而不仅仅是整天。


从Java 1.5开始,TimeUnit.DAYS.toMillis(1)对我来说看起来更干净。

1
2
3
4
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));


在Java 8中,您可以使用java.time.LocalDate

1
2
LocalDate parsedDate = LocalDate.parse("2015-10-30"); //Parse date from String
LocalDate addedDate = parsedDate.plusDays(1);   //Add one to the day field

您可以如下将其转换为java.util.Date对象。

1
Date date = Date.from(addedDate.atStartOfDay(ZoneId.systemDefault()).toInstant());

您可以将LocalDate格式化为字符串,如下所示。

1
String str = addedDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));

这很简单,尝试用一个简单的词来解释。
得到今天的日期如下

1
2
3
Calendar calendar = Calendar.getInstance();
System.out.println(calendar.getTime());// print today's date
calendar.add(Calendar.DATE, 1);

现在,通过采用(常数,值)的calendar.add方法将日期提前一天。这里的常数可以是DATE,小时,分钟,秒等,而值是常数的值。就像一天一样,提前常量为Calendar.DATE,其值为1,因为我们希望提前一天的值。

System.out.println(calendar.getTime());// print modified date which is明天的日期

谢谢


在Java 8中,简单的方法是:

1
Date.from(Instant.now().plusSeconds(SECONDS_PER_DAY))


如果要添加单个时间单位,并且希望其他字段也要增加,则可以安全地使用add方法。请参见下面的示例:

1
2
3
4
5
6
7
8
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()));

将打印:

1
2
3
1970-12-31
1971-01-01
1970-12-31


Apache Commons已经拥有了这个DateUtils.addDays(日期,整数)http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html#addDays%28java .util.Date,%20int%29,您可以使用它,也可以使用JodaTime使其更整洁。


只需在字符串中传递日期和第二天的数目

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 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;

}

使用DateFormat API将字符串转换为Date对象,然后使用Calendar API添加一天。如果您需要特定的代码示例,请告诉我,我可以更新答案。


如果您使用Java SE 8或更高版本,则应使用新的日期/时间API

1
2
3
4
5
6
 int days = 7;      
 LocalDate dateRedeemed = LocalDate.now();
 DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/YYYY");

 String newDate = dateRedeemed.plusDays(days).format(formatter);  
 System.out.println(newDate);

如果必须从java.util.Date转换为java.time.LocalDate,则可以使用此方法。

1
2
3
4
5
  public LocalDate asLocalDate(Date date) {
      Instant instant = date.toInstant();
      ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
      return zdt.toLocalDate();
  }

如果您使用的是Java SE 8之前的版本,建议您使用Joda-Time

Joda-Time provides a quality replacement for the Java date and time
classes and is the de facto standard date and time library for Java
prior to Java SE 8

1
2
3
4
5
6
   int days = 7;      
   DateTime dateRedeemed = DateTime.now();
   DateTimeFormatter formatter = DateTimeFormat.forPattern("dd/MM/YYYY");

   String newDate = dateRedeemed.plusDays(days).toString(formatter);  
   System.out.println(newDate);

如果您使用的是Java 8,java.time.LocalDatejava.time.format.DateTimeFormatter可以使这项工作非常简单。

1
2
3
4
5
6
public String nextDate(String date){
      LocalDate parsedDate = LocalDate.parse(date);
      LocalDate addedDate = parsedDate.plusDays(1);
      DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-mm-dd");
      return addedDate.format(formatter);
}


您可以从" org.apache.commons.lang3.time"使用此软件包:

1
2
3
4
 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
 Date myNewDate = DateUtils.addDays(myDate, 4);
 Date yesterday = DateUtils.addDays(myDate, -1);
 String formatedDate = sdf.format(myNewDate);


让我们澄清一下用例:您要进行日历算术并以java.util.Date开始/结束。

一些方法:

  • 使用SimpleDateFormat转换为字符串然后返回:这是一种低效的解决方案。
  • 转换为LocalDate:您将丢失任何时间信息。
  • 转换为LocalDateTime:这涉及更多步骤,您需要担心时区。
  • 使用Date.getTime()转换为纪元:这是有效的方法,但是您要以毫秒为单位进行计算。
  • 考虑使用java.time.Instant:

    1
    2
    3
    Date _now = new Date();
    Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
    Date _newDate = Date.from(_instant);


    1
    startCalendar.add(Calendar.DATE, 1); //Add 1 Day to the current Calender


    其实很简单。
    一天包含86400000毫秒。
    因此,首先您可以使用System.currentTimeMillis()从The System获取以毫秒为单位的当前时间,然后
    添加84000000 milliSeconds并使用Date类生成毫秒的日期格式。

    String Today = new Date(System.currentTimeMillis()).toString();

    今日弦乐将于2019-05-9

    String Tommorow = new Date(System.currentTimeMillis() + 86400000).toString();

    String Tommorow将在2019-05-10

    String DayAfterTommorow = new Date(System.currentTimeMillis() + (2 * 86400000)).toString();

    String DayAfterTommorow将是2019-05-11


    1
    2
    3
    Date newDate = new Date();
    newDate.setDate(newDate.getDate()+1);
    System.out.println(newDate);