The java.util.Calendar
allows us to do a date arithmetic function such as add or subtract a unit of time to the specified date field.
The method that done this process is the Calendar.add(int field, int amount)
. Where the value of the field can be Calendar.DATE
, Calendar.MONTH
, Calendar.YEAR
. So this mean if you want to subtract in days, months or years use Calendar.DATE
, Calendar.MONTH
or Calendar.YEAR
respectively.
package org.kodejava.example.util;
import java.util.Calendar;
public class CalendarAddExample {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
System.out.println("Today : " + cal.getTime());
// Subtract 30 days from the calendar
cal.add(Calendar.DATE, -30);
System.out.println("30 days ago: " + cal.getTime());
// Add 10 months to the calendar
cal.add(Calendar.MONTH, 10);
System.out.println("10 months later: " + cal.getTime());
// Subtract 1 year from the calendar
cal.add(Calendar.YEAR, -1);
System.out.println("1 year ago: " + cal.getTime());
}
}
In the code above we want to know what is the date back to 30 days ago. The sample result of the code is shown below:
Today : Sun Sep 17 07:24:29 WITA 2017
30 days ago: Fri Aug 18 07:24:29 WITA 2017
10 months later: Mon Jun 18 07:24:29 WITA 2018
1 year ago: Sun Jun 18 07:24:29 WITA 2017
Wayan Saryada
Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. If these posts help, you can support me, buy me a cup of coffee or tea. Thank you 🥳
Latest posts by Wayan Saryada (see all)
- How do I set the time of java.util.Date instance to 00:00:00? - October 24, 2019
- How to Install Consolas Font in Mac OS X? - March 29, 2019
- How do I clear the current command line in terminal? - February 14, 2019
there is a error in line number 18 semicolon missing ;