Adding and subtracting dates in Java

How to add or subtract a date in java? For example, java.sql.Date and is formatted as follows: yyyy-MM-dd, how can I add in 5 months? I saw in some tutorial that they use Calendar , is it possible to set a date on it? Please, help.

Example: 2012-01-01 when adding 5 months will be 2012-06-01 .

PS: I am a .Net programmer and am slowly learning the Java environment.

+8
java date datetime
source share
8 answers

First of all, you need to convert the String date to java.util.Date , than use java.util.Calendar to manage dates. You can also do math with milliseconds, but I do not recommend this.

 public static void main( final String[] args ) throws ParseException { final String sdate = "2012-01-01"; final SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd" ); final Date date = df.parse( sdate ); // conversion from String final java.util.Calendar cal = GregorianCalendar.getInstance(); cal.setTime( date ); cal.add( GregorianCalendar.MONTH, 5 ); // date manipulation System.out.println( "result: " + df.format( cal.getTime() ) ); // conversion to String } 
+12
source share

Eliminate the built-in Date class for date math. Take a look at JodaTime, which has a much better API for this kind of thing.

+4
source share

Use Calendar

 Calendar cal = Calendar.getInstance(); cal.add(Calendar.MONTH, 5); 
+2
source share

To convert a date to a calendar, use:

 Date date = your_date_here; Calendar cal = Calendar.getInstance(); cal.setTime(date); 

Then use the arithmetic functions of the calendar to add / subtract:

 cal.add(Calendar.MONTH, 5); 
+1
source share

Or, Convert date to time in milis. Do the math and convert millions back to date.

0
source share

use the CalenderUtils from the Google GWT package.

 import com.google.gwt.user.datepicker.client.CalendarUtil; 

...

 //now Date d = new Date(); // Now + 2 months CalendarUtil.addMonthsToDate(d, 2); 
0
source share

Another option is the DateUtils class from the third-party collection of the Apache Commons library. Example:

 Date d = DateUtils.parseDate("2012-01-01", "yyyy-MM-dd"); Date d2 = DateUtils.addMonths(d, 5); System.out.println("Old date + 5 months = " + d2); 
0
source share
-one
source share

All Articles