How do I do a date add or substract?
Category: java.util, viewed: 6229 time(s).
The java.util.Calendar allows us to do a date arithmetic function such as add or substract 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 substract in days, months or years use Calendar.DATE, Calendar.MONTH or Calendar.YEAR respectively.
import java.util.Calendar; public class CalendarAddExample { public static void main(String[] args) { Calendar cal = Calendar.getInstance(); System.out.println("Today : " + cal.getTime()); // Substract 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()); // Substract 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 : Tue Jan 03 06:53:03 ICT 2006 30 days ago: Sun Dec 04 06:53:03 ICT 2005
Related Examples
- How do I convert milliseconds value to date?
- How do I split a string using Scanner class?
- How do I read file using Scanner class?
- How do I read / write data in Windows registry?
- How do I read user input from console using Scanner class?
- How do I use ResourceBundle for i18n?
- How do I convert time between timezone?
- How do I set a default Locale?
- How do I remove duplicate element from array?
- How do I convert array to Set?
|
|