Thomas Mitchell
Thomas Mitchell

Reputation: 1071

Java Calendar add issue

I'm having an issue with the Java Calendar add() functionality. The give or take is used to provide a roundabout date for dates to depart on a travel site.

end.add(Calendar.DATE, Integer.parseInt(giveOrTake));

The code is above and the test condition I'm using is to choose 29/07/2012 as the date and 3 days give or take. According to the documentation this should come out as 01/08/2012 but it comes out at 01/07/2012.

I've checked giveOrTake when it's passed to the method and it's fine so I have no idea what is going on. I can hardcode the giveOrTake value and still get the error.

Upvotes: 3

Views: 3317

Answers (3)

Basil Bourque
Basil Bourque

Reputation: 338266

You are using troublesome old date-time classes, now legacy, supplanted by the java.time classes.

Also, you are using a date-time object to represent a date-only value, a misfit.

Using java.time

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.of( 2012 , 7 , 29 ) ;
LocalDate threeDaysLater = ld.plusDays( 3 );

ld.toString(): 2012-07-29

threeDaysLater.toString(): 2012-08-01

See code run live in IdeOne.com.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1499860

Works for me:

import java.util.*;

public class Test {
    public static void main (String []args) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(2012, Calendar.JULY, 29);
        calendar.add(Calendar.DATE, 3);
        System.out.println(calendar.getTime()); // August 1st
    }
}

My guess is that you've got the month wrong before calling add - note how my call to set above uses 6 as the month, because the call uses 0-based month numbers.

Note that as per my comment on the question, you'd be much better off moving to Joda Time if you can...

Upvotes: 5

Thomas Mitchell
Thomas Mitchell

Reputation: 1071

It was an issue with the date format. It was set as yyyymmdd when it should have been 'yyyyMMdd'.

Upvotes: -1

Related Questions