0

I am currently setting a Date using the following function.

private Date getDate (int day, int month, int year){
    Calendar calendar = Calendar.getInstance();
    calendar.set(year, month-1, day);
    Date date = calendar.getTime();
    return date;
}

However if (31, 6, 2014) is entered, the date is simply changed to the 1st of July 2014. Is there a way that I could check whether a date is valid if my input is as above?

Thanks for your help.

  • FYI, it's pretty much universally recommended to use JodaTime over Java's `Date` library. (See e.g. http://stackoverflow.com/a/589940/129570) – Oliver Charlesworth May 10 '14 at 12:43
  • Also, I think you might want to use `setLenient(true)` first. – Oliver Charlesworth May 10 '14 at 12:44
  • see http://stackoverflow.com/questions/7606387/what-is-the-use-of-lenient – Arturo Volpe May 10 '14 at 12:44
  • what do you mean by valid date? can you explain? – Hirak May 10 '14 at 12:45
  • @Hirak: Isn't the OP's example fairly self-explanatory? 31st June does not exist. – Oliver Charlesworth May 10 '14 at 12:46
  • You could simply get the day, month and year from the created calendar, and check if they're the same as the original ones. – JB Nizet May 10 '14 at 12:47
  • @Giri, if you are satisfied with the answer, please set the answer as correct and an upvote would be nice :) – Gabriel Ruiu May 11 '14 at 08:59
  • @Oli, the phrase "universally recommended" is incorrect and claims false authority in my opinion. "Commonly recommended" is fair, but the Calendar class does its job very well and is far from universally rejected. Joda and java.time are just easier to work with. There are many situations where adding a dependency on any third-party library is costly or even prohibited. – VGR May 11 '14 at 13:13

1 Answers1

4

Reason why you get 1st of July 2014 as output:

  • when you set the month as month-1, in this case you're setting the month as June, because the month parameter in the calendar.set() method is 0-based (January has the index 0)
  • June has 30 calendar days, so if you set the day as 31, it will overflow into July 1st; if you would've set 44 as the number of days, the output would be 14th of July 2014

To counteract this, set lenient to false:

calendar.setLenient(false);

and an exception will be thrown if the dates are out of bounds

Gabriel Ruiu
  • 2,753
  • 2
  • 19
  • 23