JAL Computing

C++COMProgramming .NET Mac Palm CPP/CLI Hobbies

 

Home
Up

 

C++ Date Algorithms

The following algorithms may be useful for calendar functions:

bulletIsLeapYear
bulletGetFirstDayInMonth
bulletGetDaysInMonth

IsLeapYear

// ASSERT Year>0
BOOL CCalendar::IsLeapYear(const unsigned int Year)
{
    return ((Year%4 == 0)&&(Year%100 != 0))||(Year%400 == 0);
}

GetFirstDayInMonth

// Days since Sunday 0-6
// Based on Zeller
// ASSERT Year>1, Month>=1 && <=12.
int CCalendar::GetFirstDayInMonth(unsigned int Year, unsigned int Month)
{
    const int day=1;
    if (Month < 3) {
        Month +=12;
        Year -= 1;
    }
    return ((day+1+(Month*2)+(int)((Month+1)*3/5)+Year+(int)(Year/4)-(int)(Year/100)+(int)(Year/400))%7);
}

GetDaysInMonth

// ASSERT Month 1-12
// ASSERT Year>0
int CCalendar::GetDaysInMonth(const unsigned int Year, const unsigned int Month)
{
    switch(Month) {
        case 2: // Februrary
            if (IsLeapYear(Year)) {
                return 29;
            }
            else {
                return 28;
            }
            break;
        case 4: // April Falls Through
        case 6: // June
        case 9: // September
        case 11: // November
            return 30;
            break;
        default:
            return 31;
    }
}

 

Send mail to [email protected] with questions or comments about this web site. Copyright © 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 © 
Last modified: 08/04/09
Hosted by www.Geocities.ws

1