特定年份和月份的打印日历

时间:2016-10-18 03:04:06

标签: c calendar

我正在尝试打印特定年份和月份的日历,但每个月都会获得相同的日历。我还尝试添加一个声明,看看年份是否是闰年增加的天数,但没有任何区别。我是新手。请帮忙提出任何建议。提前谢谢。

    void print_month_calendar(int year, int month)
{
    int day;
    int daycode = ddaycode(year);
    int days_in_month[]={0,31,28,31,30,31,30,31,31,30,31,30,31};

char *months[]=
            {
                    " ",
                    "\n\n\nJanuary",
                    "\n\n\nFebruary",
                    "\n\n\nMarch",
                    "\n\n\nApril",
                    "\n\n\nMay",
                    "\n\n\nJune",
                    "\n\n\nJuly",
                    "\n\n\nAugust",
                    "\n\n\nSeptember",
                    "\n\n\nOctober",
                    "\n\n\nNovember",
                    "\n\n\nDecember"
            };

    printf("%s", months[month]);
    printf("\n\nSun  Mon  Tue  Wed  Thu  Fri  Sat\n");

    if(( year%4==0 && year%100 !=0) || year%400==0)
        days_in_month[2] = 29;

    for (day = 1; day <= 1 + daycode * 5; day++)
    {
        printf(" ");
    }

    //Print all the dates for the month
    for (day = 1; day <= days_in_month[month]; day++)
    {
        printf("%2d", day);

        if ((day + daycode) % 7 > 0)
            printf("   ");
        else
            printf("\n ");
    }
}

int ddaycode(int year)
{
    int daycode;
    int d1, d2, d3;

    d1 = (year - 1.)/ 4.0;
    d2 = (year - 1.)/ 100.;
    d3 = (year - 1.)/ 400.;
    daycode = (year + d1 - d2 + d3) %7;
    return daycode;
}

1 个答案:

答案 0 :(得分:1)

你必须知道这个月的第一个工作日。您可以使用localtime转到特定日期,使用mktime获取包含工作日的struct tm数据。此外,您可以使用strftime获取月份名称。例如:

void print_month_calendar(int year, int month)
{
    time_t rawtime;
    struct tm * timeinfo;
    time(&rawtime);
    timeinfo = localtime(&rawtime);
    timeinfo->tm_year = year - 1900;
    timeinfo->tm_mon = month - 1;
    timeinfo->tm_mday = 1;
    mktime(timeinfo);

    //sunday is 1 ... saturday is 7
    int weekday = 1 + timeinfo->tm_wday;

    int days_in_month[] = { 0, 31,28,31,30,31,30,31,31,30,31,30,31 };
    if ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0))
        days_in_month[2]++;

    char monthname[30];
    strftime(monthname, sizeof(monthname), "%B", timeinfo);

    printf(" %s %d\n", monthname, year);
    printf(" Su  Mo  Tu  We  Th  Fr  Sa\n");

    int day = 1;
    for (int i = 1; i <= 40; i++)
    {
        if (i < weekday)
        {
            printf("    ");
        }
        else
        {
            printf("%3d ", day);
            if (day == days_in_month[month])
                break;
            day++;
            if ((i % 7) == 0)
                printf("\n");
        }
    }

    printf("\n");
}


int main()
{
    print_month_calendar(2016, 10);
    return 0;
}

ideone example

 October 2016
 Su  Mo  Tu  We  Th  Fr  Sa
                          1 
  2   3   4   5   6   7   8 
  9  10  11  12  13  14  15 
 16  17  18  19  20  21  22 
 23  24  25  26  27  28  29 
 30  31