Addition and Subtraction of Dates in Java

date, datetime, java

Solution

First of all you have to convert your `String` date to `java.util.Date`, than you have to use `java.util.Calendar` to manipulate dates. It is also possible to do math with millis, 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
}

Problem

How can we add or subtract date in java? For instance `java.sql.Date` and formatted like this: yyyy-MM-dd, how can i Add 5 months from that? I've seen in some tutorial that they are using `Calendar`, can we set date on it? Please Help. Example: `2012-01-01` when added 5 months will become `2012-06-01`. PS: I'm a .Net Programmer and slowly learning to Java environment.

Original source