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

2018-12-31 01:23发布

I'm working with a date in this format: yyyy-mm-dd.

How can I increment this date by one day?

标签: java date
25条回答
不流泪的眼
2楼-- · 2018-12-31 02:16

you can use Simple java.util lib

Calendar cal = Calendar.getInstance(); 
cal.setTime(yourDate); 
cal.add(Calendar.DATE, 1);
yourDate = cal.getTime();
查看更多
素衣白纱
3楼-- · 2018-12-31 02:16

It's very simple, trying to explain in a simple word. get the today's date as below

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

Now set one day ahead with this date by calendar.add method which takes (constant, value). Here constant could be DATE, hours, min, sec etc. and value is the value of constant. Like for one day, ahead constant is Calendar.DATE and its value are 1 because we want one day ahead value.

System.out.println(calendar.getTime());// print modified date which is tomorrow's date

Thanks

查看更多
泛滥B
4楼-- · 2018-12-31 02:17
long timeadj = 24*60*60*1000;
Date newDate = new Date (oldDate.getTime ()+timeadj);

This takes the number of milliseconds since epoch from oldDate and adds 1 day worth of milliseconds then uses the Date() public constructor to create a date using the new value. This method allows you to add 1 day, or any number of hours/minutes, not only whole days.

查看更多
心情的温度
5楼-- · 2018-12-31 02:17

Apache Commons already has this DateUtils.addDays(Date date, int amount) http://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/time/DateUtils.html#addDays%28java.util.Date,%20int%29 which you use or you could go with the JodaTime to make it more cleaner.

查看更多
梦该遗忘
6楼-- · 2018-12-31 02:18

Since Java 1.5 TimeUnit.DAYS.toMillis(1) looks more clean to me.

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));
查看更多
刘海飞了
7楼-- · 2018-12-31 02:19

Let's clarify the use case: You want to do calendar arithmetic and start/end with a java.util.Date.

Some approaches:

  1. Convert to string and back with SimpleDateFormat: This is an inefficient solution.
  2. Convert to LocalDate: You would lose any time-of-day information.
  3. Convert to LocalDateTime: This involves more steps and you need to worry about timezone.
  4. Convert to epoch with Date.getTime(): This is efficient but you are calculating with milliseconds.

Consider using java.time.Instant:

Date _now = new Date();
Instant _instant = _now.toInstant().minus(5, ChronoUnit.DAYS);
Date _newDate = Date.from(_instant);
查看更多
登录 后发表回答