C 語言初學教材 - 第五章 處理時間的函數2 範例程式碼及編譯執行

範例程式碼



#include <stdio.h>
#include <time.h>

struct my_tm {
    int year;  // 現在年份
    int month; // 月份
    int day;   // 日期
    int hour;  // 二十四小時制的時
    int isam;  // 上午為非 0 值,下午為 0
    int hourt; // 十二小時制的時
    int min;   // 分
    int sec;   // 秒
};

typedef struct my_tm My_Time;

void myTimeS2(My_Time *nowPtr);

int main(void)
{
    My_Time now;
    myTimeS2(&now); 
    
    printf("\n\n現在時間是西元 %d 年 %d 月 %d 日", now.year, now.month, now.day);
    printf("%s %d 點 %d 分 %d 秒\n\n", now.isam ? "上午" : "下午", now.hourt, now.min, now.sec);
    
    return 0;
}

void myTimeS2(My_Time *nowPtr)
{
    time_t seconds = time(NULL);
    struct tm *tmPtr = localtime(&seconds);
    
    nowPtr->year = tmPtr->tm_year + 1900;
    nowPtr->month = tmPtr->tm_mon + 1;
    nowPtr->day = tmPtr->tm_mday;
    nowPtr->hour = tmPtr->tm_hour;
    if (nowPtr->hour < 12 ) {
        nowPtr->isam = 1;
        nowPtr->hourt = tmPtr->tm_hour;
    }
    else {
        nowPtr->isam = 0;
        nowPtr->hourt = tmPtr->tm_hour - 12;
    }
    nowPtr->min = tmPtr->tm_min;
    nowPtr->sec = tmPtr->tm_sec;
}

/* 《程式語言教學誌》的範例程式
    http://pydoing.blogspot.com/
    檔名:timetest3.c
    功能:示範結構的使用
    作者:張凱慶
    時間:西元2010年7月 */


編譯後執行,結果如下



程式說明,請繼續參考




沒有留言: