Search code examples
androidcalendar

How to handle leap and common years


One of the functionalities that my app provide is scheduling a specific event for the next day and I am getting the next day date using the following code:

TimeZone timeZone = TimeZone.getTimeZone("GMT+05:30");
Calendar date = Calendar.getInstance();
date.setTimeZone(timeZone);
String refreshDate = (date.get(Calendar.DAY_OF_MONTH) + 1) + "/" + 
                     (date.get(Calendar.MONTH) + 1) + "/" + 
                     date.get(Calendar.YEAR) + "," + 
                     "12:00:0";

Problem is: if it is a common year February is 28 days and if it is a leap year February is 29 days, so if today is the 28th of February the next day will be the first of March in a common year and 29th of February in case of a leap year. How to handle this ? ... in other words how to detect leap and common years ?


Solution

  • You should be able to find a leap year just by casting to GregorianCalendar as follows:

    GregorianCalendar cal = (GregorianCalendar) cal;
    
    if(cal.isLeapYear(year))
    {
        System.out.print("Given year is leap year.");
    }
    else
    { 
        System.out.print("Given year is not leap year.");
    
    }