人工知性を作りたい

私が日々、挑戦したことや学んだことなどを紹介していく雑記ブログです。 (新しいAI技術HTM, 専門の音声信号処理, 趣味のアニメ等も書いてます。)

【ソースコード置き場】現在時刻の計算 年・月・日・時・分・秒【C言語・自作】

f:id:hiro-htm877:20190601202549p:plain

アルゴリズムなどの説明は以下の記事で!

www.hiro877.com

 

ソースコード

void enshu0610(void);
struct current_time_st{
    int sec;
    int min;
    int hour;
    int day;
    int month;
    int year;
};
void calc_current_time(struct current_time_st *current_t);
int judge_leap_year(int year);
int main() {
    enshu0610();
    return 0;
}
int judge_leap_year(int year){
    if(((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)){
        return 1;
    }
    else{
        return 0;
    }
}


void calc_current_time(struct current_time_st *current_t){
    
    long int t = 0;
    long int t_tmp = 0;
    
    int year = 1970;
    
    t = time(&t);
    
    current_t->sec = t % 60;
    t_tmp = t / 60;
    
    current_t->min = t_tmp % 60;
    t_tmp = t_tmp / 60;
    
    //japan time = グリニッジ標準時(GMT) + 9
    current_t->hour = t_tmp % 24 + 9;
    t_tmp = t_tmp / 24;
    
    while(t_tmp > 365){
        if(judge_leap_year(year)){
            t_tmp -= 366;
        }
        else{
            t_tmp -=365;
        }
        year++;
    }
    
    current_t->year = year;
    
    int month_daynum_array[] ={31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if(judge_leap_year(year)){
        month_daynum_array[1]++;
    }else{
        //do nothing
    }
    
    int i;
    for(i=0; i<12; i++){
        if(t_tmp - month_daynum_array[i] > 0){
            t_tmp -= month_daynum_array[i];
        }
        else{
            break;
        }
    }
    current_t->month = i+1;
    current_t->day = t_tmp+1;
    
}


void enshu0610(void){
    struct current_time_st current_t;
    calc_current_time(&current_t);
    printf("---japan time---\n");
    printf("current time is:\n");
    printf("%d年 %d月 %d日 %d時 %d分 %d秒\n", current_t.year, current_t.month, current_t.day, current_t.hour, current_t.min, current_t.sec);
    //既存の関数
    time_t t = time(NULL);
    printf("%s", ctime(&t));
}