【c语言】简易日历

#include

#include

 

int main() {

    time_t t = time(NULL);

    struct tm *tm = localtime(&t);

 

    int year = tm->tm_year + 1900;

    int month = tm->tm_mon + 1;

 

    printf("当前日期:%d年%d月\n", year, month);

 

    struct tm firstDay;

    firstDay.tm_year = year - 1900;

    firstDay.tm_mon = month - 1;

    firstDay.tm_mday = 1;

    mktime(&firstDay);

 

    int weekday = firstDay.tm_wday;

 

    printf("日 一 二 三 四 五 六\n");

    

    for (int i = 0; i < weekday; i++) {

        printf(" ");

    }

 

    int daysInMonth;

    switch (month) {

        case 2:

            if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))

                daysInMonth = 29;

            else

                daysInMonth = 28;

            break;

        case 4:

        case 6:

        case 9:

        case 11:

            daysInMonth = 30;

            break;

        default:

            daysInMonth = 31;

    }

 

    for (int day = 1; day <= daysInMonth; day++) {

        printf("%2d ", day);

        if ((weekday + day) % 7 == 0)

            printf("\n");

    }

 

    return 0;

}

你可能感兴趣的:(C)