9

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.

10 Answers 10

14

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
}
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

2

Use Calendar

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 5);

2 Comments

Sir what does getInstance do? How can i set cal to 2012-01-01?
getInstance() is a factory method it would initilize calendar with current date and time of system, you could use setTime() method to set any date, see java doc
2

java.time

The accepted answer uses java.util date-time API and SimpleDateFormat which was the correct thing to do in 2012. In Mar 2014, the java.util date-time API and their formatting API, SimpleDateFormat were supplanted by the modern date-time API. Since then, it is highly recommended to stop using the legacy date-time API.

Solution using java.time, the modern date-time API:

You do not need a DateTimeFormatter for your date string: java.time API is based on ISO 8601 and therefore you do not need to specify a DateTimeFormatter to parse a date-time string which is already in ISO 8601 format e.g. your date string, 2012-01-01 which can be parsed directly into a LocalDate instance, that contains just date units.

Having parsed the date string into LocalDate, you can add or subtract different date units e.g. years, months, days etc. to it.

Demo:

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

class Main {
    public static void main(String args[]) {
        LocalDate date = LocalDate.parse("2012-01-01");
        System.out.println(date);

        LocalDate afterFiveMonths = date.plusMonths(5);
        LocalDate beforeFiveMonths = date.minusMonths(5);
        System.out.println(afterFiveMonths);
        System.out.println(beforeFiveMonths);

        // Alternatively,
        afterFiveMonths = date.plus(5, ChronoUnit.MONTHS);
        beforeFiveMonths = date.minus(5, ChronoUnit.MONTHS);
        System.out.println(afterFiveMonths);
        System.out.println(beforeFiveMonths);
    }
}

Output:

2012-01-01
2012-06-01
2011-08-01
2012-06-01
2011-08-01

ONLINE DEMO

Learn more about the modern Date-Time API from Trail: Date Time.

Comments

1

To convert a Date to a Calendar, use:

Date date = your_date_here;

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

Then use the calendar arithmetic functions to add/subtract:

cal.add(Calendar.MONTH, 5);

Comments

0

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

Comments

0

use CalenderUtils from google's package GWT.

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

...

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

1 Comment

Your proposal to add 5 months to a date is to add the whole of GWT to a project?
0

Another option is the DateUtils class from the 3rd party Apache Commons library collection. 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);

Comments

0

There are various ways. One of them could be with joda.time. This does not answer the question by using Calendar but one of the other approach if needed by someone. :D

import java.sql.Date;
import org.joda.time.DateTime;
//
DateTime datetime = new DateTime("2012-01-01");
Date dt = new Date(datetime.plusMonths(5).toDate().getTime());
System.out.println(dt);
// This gives output as 2012-06-01

PS: Happy coding with Java

2 Comments

Not bad if someone does need a Date in 2022 (or later). Which shouldn’t be the case, though, since the Date class is long outdated and poorly designed, nothing that anyone should use any more. Also, while Joda-Time was a good library, it has now been officially replaced by java.time, the modern Java date and time API. See the answer by Arvind Kumar Avinash.
You are right. joda.time is replaced by java.time (they even ask you to migrate to this). It was used before the release of Java 8 and as this was an old question from 2012, I answered it. Thanks for your comment.
-1

The complete program that does date addition is in http://dwbitechguru.blogspot.ca/2014/09/jave-program-to-add-or-substract-dates.html

1 Comment

as @Parixit pointed out, normally we try explain the big lines of links like that. If the link ever goes down your answer becomes useless for the community. If you could edit it to add the important parts, it would make a valid answer :) thx ^^

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.