Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if the date is valid using Calendar

Tags:

java

I want to use calendars method to set year date and month but want some kind of indication if the date is invalid e.g.

calendar.set(2013,Calendar.JANUARY , 23) //is a valid date
calendar.set(2013,Calendar.JANUARY , 33) //is not

I set calendar.setLenient(false) and expected that setting the value to January 33rd would throw an exception, but it did not.

like image 671
user1411335 Avatar asked Jul 02 '13 21:07

user1411335


People also ask

How do you check a date is valid or not?

Given date in format date, month and year in integer. The task is to find whether the date is possible on not. Valid date should range from 1/1/1800 – 31/12/9999 the dates beyond these are invalid. These dates would not only contains range of year but also all the constraints related to a calendar date.

How do you check if a date is a valid date in Java?

DateValidator validator = new DateValidatorUsingDateFormat("MM/dd/yyyy"); assertTrue(validator. isValid("02/28/2019")); assertFalse(validator. isValid("02/30/2019")); This was the most common solution before Java 8.

What is a date validation?

date of validation means the date when the Referred Party has successfully validated his/her identity and fully completed the on-boarding procedures.


2 Answers

It seems the check is done lazily:

A non-lenient GregorianCalendar throws an exception upon calculating its time or calendar field values if any out-of-range field value has been set.

So this will throw you an exception:

Calendar c = new GregorianCalendar();
c.setLenient(false);
c.set(2013, Calendar.JANUARY, 33);
c.getTime();

But not without the getTime.

like image 183
zw324 Avatar answered Sep 30 '22 00:09

zw324


Leniency merely controls whether or not the calendar accepts out-of-range dates. If leniency is set, Java will do some math to adjust out-of-range dates (for example, 2013-12-32 becomes 2014-01-01). If leniency is not set, Java will not allow this, but it doesn't check for out-of-range data until you actually request some of the fields. From the Javadocs:

A non-lenient GregorianCalendar throws an exception upon calculating its time or calendar field values if any out-of-range field value has been set.

To your question then:

How do I handle this?

You can set the calendar to the first of the month:

calendar.set(2013, Calendar.JANUARY, 1);

and then invoke

int days = calendar.getActualMaximum(Calendar.DAY_OF_MONTH); 

and compare against your day value. If your day value is in range, then you can proceed.

like image 26
jason Avatar answered Sep 30 '22 01:09

jason