カレンダーの表示

カレンダーの表示(list_21.c)
#include <stdio.h>
#include <time.h>

//-----------------------------------------------------------------
int wyoubi(int y,int m,int d);
void disp_cal(struct tm tm);
//-----------------------------------------------------------------

int main()
{
    time_t t;
    struct tm *tm;
    t  = time(NULL);
    tm = localtime(&t);
    disp_cal(*tm);
    return 0;
}

//-----------------------------------------------------------------
// 曜日の計算
//-----------------------------------------------------------------
int wyoubi(int y,int m,int d)
{
    int wd;
    if(m<3){ y=y-1; m=m+12; }
    m = ((m*13)+8)/5+y;
    y=y/4; m=m+y;  y=y/25; m=m-y;
    y=y/4; m=+y+d; d=m%7;  wd=d*2+1;
    wd /= 2;
    return wd;
}
//-----------------------------------------------------------------
// カレンダーの表示
//-----------------------------------------------------------------
void disp_cal(struct tm tm)
{
    int i,j,y,m,d,wd;
    static int mend[]={31,28,31,30,31,30,31,31,30,31,30,31};
    static char* Wdy[]={"Su","Mo","Tu","We","Th","Fr","Sa"};
    static char* Mon[]={
        "January","February","March","April","May","June","July",
        "August","September","Octover","November","December"
    };
    y  = tm.tm_year+1900;
    m  = tm.tm_mon;
    d  = tm.tm_mday;
    wd = wyoubi(y,m+1,d);
    // 閏年の判定
    if((y%4==0) && (y%100!=0) || (y%400==0)) mend[1]=29;
    // 表示
    for(i=0;i<14-strlen(Mon[m]);i++) printf(" ");
    printf("%s %d:\n",Mon[m],y);
    for(i=0;i<7;i++) printf("%s ",Wdy[i]);
    printf("\n");
    for(i=0;i<wd;i++) printf("   ");
    // 第一週
    d = 1;
    for(i=wd;i<7;i++) printf("%2d ",d++);
    printf("\n");
    // 残りの週
    for(i=0;i<4;i++){
        for(j=0;j<7;j++){
            if(d>mend[m-1]){
                printf("\n"); return;
            }
            printf("%2d ",d++);
        }
        printf("\n");
    }
}

実行結果
      November 2004:
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 
inserted by FC2 system