Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

Linux time 相關 API 整理:時間戳與 tm 結構的互轉

一、函數原型

#include <time.h>

time_t time(time_t *t);
char *asctime(const struct tm *tm);
char *ctime(const time_t *timep);
struct tm *gmtime(const time_t *timep);
struct tm *localtime(const time_t *timep);
time_t mktime(struct tm *tm);
char *strptime(const char *s, const char *format, struct tm *tm);
size_t strftime(char *s, size_t max, const char *format, const struct tm *tm);

struct tm {
    int tm_sec;   /* 秒 */
    int tm_min;   /* 分 */
    int tm_hour;  /* 時 */
    int tm_mday;  /* 日 */
    int tm_mon;   /* 月,0 起算 */
    int tm_year;  /* 年,從 1900 起算 */
    int tm_wday;  /* 星期 */
    int tm_yday;  /* 一年中的第幾天 */
    int tm_isdst; /* 日光節約時間標誌 */
};

二、API 分類

  • time():取得當前時間戳;若傳入的 t 非空,結果同時寫入該位址。
  • asctime():傳入 tm 結構,回傳可讀字串。
  • ctime():功能與 asctime 相同,但入口是 time_t 時間戳,一步完成轉換。
  • gmtime():時間戳轉 tm,結果為 UTC 時間,不含本地時區偏移。
  • localtime():同上,但結果為本機時區時間。
  • mktime():反向操作,tm 轉時間戳。
  • strftime():按格式字串把 tm 輸出為字串。
  • strptime():按格式字串把字串解析為 tm。

記法很簡單:asctime 與 ctime 一組(字串輸出),gmtime 與 localtime 一組(差別只在時區),strftime 與 strptime 一組(格式化與解析),time 負責取當前時刻。

注意 tm 中兩個「偏移量」欄位:tm_mon 從 0 開始,tm_year 是「減去 1900」的年數,輸出時記得補回。

三、完整示例

#include <stdio.h>
#include <stdlib.h>
#define _XOPEN_SOURCE   /* 少了這行,strptime 會出現隱式宣告警告 */
#include <time.h>

time_t return_current_time();
void print_time(time_t tdata);

int main(int argc, char *argv[])
{
    print_time(return_current_time());
    return EXIT_SUCCESS;
}

void print_time(time_t tdata)
{
    char *wday[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
    struct tm *pt;
    time_t tmp;
    char buf[256];
    char *format = "%A %d %B, %I:%S %p";

    pt = localtime(&tdata);          /* 改為 gmtime 則輸出 UTC */

    printf("%ld: convert to time:\n", tdata);
    printf("isdst:%d\n", pt->tm_isdst);
    printf("year:%d\n", pt->tm_year + 1900);
    printf("mon:%d\n",  pt->tm_mon + 1);
    printf("mday:%d\n", pt->tm_mday);
    printf("week:%s\n", wday[pt->tm_wday]);
    printf("hour:%d\n", pt->tm_hour);
    printf("min:%d\n",  pt->tm_min);
    printf("sec:%d\n",  pt->tm_sec);

    printf("asctime:\n%s\n", asctime(pt));
    printf("ctime:\n%s\n", ctime(&tdata));

    if ((tmp = mktime(pt)) == -1) {
        perror("mktime error:");
        exit(1);
    }
    printf("mktime convert to time_t:%ld\n", tmp);

    if (strftime(buf, 256, format, pt) == 0) {
        perror("strftime error:");
        exit(1);
    }
    printf("strftime: %s\n", buf);

    strptime(buf, format, pt);   /* 依 format 把字串解析回 tm */
}

time_t return_current_time()
{
    return time((time_t *)0);
}

幾個實務提醒

asctime 與 ctime 回傳的是靜態緩衝區位址,非執行緒安全,多執行緒環境請改用 asctime_r / ctime_r。gmtime 與 localtime 同樣有此問題,對應的 gmtime_r、localtime_r 才是安全版本。另外 strftime 失敗時回傳 0 而非 -1,判斷方式與直覺不同,需特別留意。

Copyright © Linux教程網 All Rights Reserved