How to get next day and previous day in Java when we know some date? For example, suppose getBatchDate() = 2014-08-21
. How to get previous day and next day with lesser code?
Asked
Active
Viewed 2,342 times
-2
-
Try using joda-time framework. It comes with handy methods. – Maas Sep 03 '14 at 11:31
-
Don't bother with joda-time for this. As the two correct answers here demonstrate, this can be done without it. – Dawood ibn Kareem Sep 03 '14 at 18:07
-
Possible duplicate of [How can I increment a date by one day in Java?](http://stackoverflow.com/questions/428918/how-can-i-increment-a-date-by-one-day-in-java) – jww Sep 04 '14 at 07:09
3 Answers
2
Use calendar to add values:
Calendar cal = new GregorianCalendar();
cal.setTime(getBatchDate());
cal.add(Calendar.DAY_OF_MONTH, 1);
Date nextDay = cal.getTime();
cal.setTime(getBatchDate());
cal.add(Calendar.DAY_OF_MONTH, -1);
Date prevDay = cal.getTime();

Jens
- 67,715
- 15
- 98
- 113
0
Use Calendar#add()
method where first argument is DATE
and second value is either 1 or -1 based on next or previous day.
sample code:
Calendar cal=Calendar.getInstance();
cal.setTime(date); // set the date
//cal.add(Calendar.DATE, 1); // next day
cal.add(Calendar.DATE, -1); // prev day
System.out.println(cal.getTime());

Braj
- 46,415
- 5
- 60
- 76
0
I would include Joda DateTime in your pom You can make a DateTime object, which has methods add or minus a day, and its actually quite reliable.
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>2.4</version>
</dependency>

Pienterekaak
- 456
- 2
- 7
-
Actually if you insist on using Joda-time, which in this case is entirely unnecessary, the correct class to use is `LocalDate`, not `DateTime`. The correct method to use is `plusDays`, in the `LocalDate` class. If you're going to recommend a tool, please at least recommend the correct use of the tool. – Dawood ibn Kareem Sep 05 '14 at 12:20