Search code examples
javadategregorian-calendar

Java - GregorianCalendar


I'm using the GregorianCalendar in Java, and I am wondering how I can use this to check whether or not a date is valid (E.g.: to check if Feb 29th is only in leap year, to check if the date is no sooner than the current data, etc).

I have created a GregorianCalendar object and passed it the values of the data I would like to check as follows:

GregorianCalendar cal1 = new GregorianCalendar(day,month,year);

If the date is valid, I'd like to return true. How could I do this?


Solution

  • Basic Idea: if you try to set the invalid date to Calendar instance, it would make it correct one,

    For example if you set 45 as date it would not be the same once you set and retrieve

    public boolean isValid(int d, int m, int y){
        //since month is 0 based
        m--;
        //initilizes the calendar instance, by default the current date
        Calendar cal = Calendar.getInstance();
        //resetting the date to the one passed
        cal.set(Calendar.YEAR, y);
        cal.set(Calendar.MONTH, m);
        cal.set(Calendar.DATE, d);
    
        //now check if it is the same as we set then its valid, not otherwise
        if(cal.get(Calendar.DATE)==d &&cal.get(Calendar.MONTH) ==m && cal.get(Calendar.YEAR) ==y){
          return true;
        }
        //changed so not valid 
        return false;
    
    }