Let's look at various ways to add a date to a Date.
Since Date is a time measured based on the year 1970, date operation was performed using Calendar
.
Add and subtract dates from current time
This is the code to add the month and day to the Date
object that holds the current time.
The current Date is set in Calendar and date operation is performed with add()
. To subtract a date, simply put a negative number.
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Example {
public static void main(String args[]) {
Calendar cal = Calendar.getInstance();
cal.setTime(new Date());
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("current: " + df.format(cal.getTime()));
cal.add(Calendar.MONTH, 2);
cal.add(Calendar.DATE, -3);
System.out.println("after: " + df.format(cal.getTime()));
}
}
result
current: 2019-03-23
after: 2019-05-20
Add to and subtract from specific dates
Same as above, but different to generate a Date
of a specific date. This time we also did date and time calculations.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Example {
public static void main(String args[]) {
Calendar cal = Calendar.getInstance();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ");
Date date = null;
try {
date = df.parse("2019-07-04T12:30:30+0530");
} catch (ParseException e) {
e.printStackTrace();
}
cal.setTime(date);
System.out.println("current: " + df.format(cal.getTime()));
cal.add(Calendar.YEAR, 1);
cal.add(Calendar.MONTH, 2);
cal.add(Calendar.DATE, 3);
cal.add(Calendar.HOUR_OF_DAY , 1);
cal.add(Calendar.MINUTE, 20);
cal.add(Calendar.SECOND, 10);
System.out.println("after: " + df.format(cal.getTime()));
}
}
result
current: 2019-07-04T16:00:30+0900
after: 2020-09-07T17:20:40+0900
Add two dates
To add two dates, you need to use two calendars. You can get the date with Calendar.get
.
By applying the above code, you can implement it as follows. In MONTH, 0 means January (zero based), so you need to add 1 when performing calculations.
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Example {
public static void main(String args[]) {
Calendar cal = Calendar.getInstance();
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
cal.setTime(df.parse("2019-07-04"));
} catch (ParseException e) {
e.printStackTrace();
}
Calendar cal2 = Calendar.getInstance();
cal2.setTime(new Date());
System.out.println("cal: " + df.format(cal.getTime()));
System.out.println("cal2: " + df.format(cal2.getTime()));
cal.add(Calendar.YEAR, cal2.get(Calendar.YEAR));
cal.add(Calendar.MONTH, cal2.get(Calendar.MONTH) + 1); // Zero-based months
cal.add(Calendar.DATE, cal2.get(Calendar.DATE));
System.out.println("after cal: " + df.format(cal.getTime()));
System.out.println("after cal2: " + df.format(cal2.getTime()));
}
}
result
cal: 2019-07-04
cal2: 2019-03-23
after cal: 4038-10-27
after cal2: 2019-03-23
Clean up
We have seen how to perform date operation on Date using Calendar.
Related Posts
- Java - Remove items from List while iterating
- Java - How to find key by value in HashMap
- Java - Update the value of a key in HashMap
- Java - How to put quotes in a string
- Java - How to put a comma (,) after every 3 digits
- BiConsumer example in Java 8
- Java 8 - Consumer example
- Java 8 - BinaryOperator example
- Java 8 - BiPredicate Example
- Java 8 - Predicate example
- Java 8 - Convert Stream to List
- Java 8 - BiFunction example
- Java 8 - Function example
- Java - Convert List to Map
- Exception testing in JUnit
- Hamcrest Collections Matcher
- Hamcrest equalTo () Matcher
- AAA pattern of unit test (Arrange/Act/Assert)
- Hamcrest Text Matcher
- Hamcrest Custom Matcher
- Why Junit uses Hamcrest
- Java - ForkJoinPool
- Java - How to use Futures
- Java - Simple HashTable implementation
- Java - Create a file in a specific path
- Java - Mockito의 @Mock, @Spy, @Captor, @InjectMocks
- Java - How to write test code using Mockito
- Java - Synchronized block
- Java - How to decompile a ".class" file into a Java file (jd-cli decompiler)
- Java - How to generate a random number
- Java - Calculate powers, Math.pow()
- Java - Calculate the square root, Math.sqrt()
- Java - How to compare String (==, equals, compare)
- Java - Calculate String Length
- Java - case conversion & comparison insensitive (toUpperCase, toLowerCase, equalsIgnoreCase)