time_t:日曆時間,自紀元(1970-01-01 00:00:00 UTC)至今的秒數(通常為有符號 64 位整數)。
struct tm:分解時間(日曆時間分量):
struct tm {
int tm_sec; // 秒 [0,59]
int tm_min; // 分 [0,59]
int tm_hour; // 時 [0,23]
int tm_mday; // 日 [1,31]
int tm_mon; // 月 [0,11] 0=一月
int tm_year; // 年-1900 如 2024 → 124
int tm_wday; // 星期 [0,6] 0=週日
int tm_yday; // 年內天數 [0,365]
int tm_isdst; // 夏令時標誌 >0生效 =0不生效 <0未知
};
| 函數 | 功能 | 返回值 |
|---|---|---|
time(time_t *t) | 獲取當前日曆時間 | time_t(同參數輸出) |
localtime(const time_t *t) | 轉為本地時間 tm | struct tm* 靜態緩衝區 |
gmtime(const time_t *t) | 轉為 UTC 時間 tm | struct tm* 靜態緩衝區 |
mktime(struct tm *tm) | 本地 tm → time_t(修正字段) | time_t,錯誤返回 -1 |
asctime(const struct tm *tm) | tm → 固定格式字符串 | char* "Www Mmm dd hh:mm:ss yyyy\n" |
ctime(const time_t *t) | 等價 asctime(localtime(t)) | char* |
#include <stdio.h> #include <time.h>
int main() {
time_t now = time(NULL);
struct tm *lt = localtime(&now);
char *wday[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
printf("%d/%02d/%02d %s %02d:%02d:%02d\n",
1900+lt->tm_year, lt->tm_mon+1, lt->tm_mday,
wday[lt->tm_wday],
lt->tm_hour, lt->tm_min, lt->tm_sec);
return 0;
}
// 輸出:2024/06/03 Fri 21:25:34
size_t strftime(char *buf, size_t max, const char *fmt, const struct tm *tm)
char buf[64];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", lt);
printf("now = %s\n", buf); // 2024-06-03 21:23:07
| 符號 | 含義 | 示例 |
|---|---|---|
| %Y | 完整年份 | 2024 |
| %m | 兩位月份 | 06 |
| %d | 兩位日期 | 03 |
| %H | 24制時 | 21 |
| %M | 分 | 23 |
| %S | 秒 | 07 |
| %F | %Y-%m-%d 簡寫 | 2024-06-03 |
| %T | %H:%M:%S 簡寫 | 21:23:07 |
| %A / %a | 星期全稱/縮寫 | Monday / Mon |
| %B / %b | 月份全稱/縮寫 | June / Jun |
| %z / %Z | 時區偏移/名稱 | +0800 / CST |
int gettimeofday(struct timeval *tv, struct timezone *tz)(POSIX,非標準 C)
struct timeval {
time_t tv_sec; // 秒
suseconds_t tv_usec; // 微秒
};
struct timezone { // 通常傳 NULL 忽略
int tz_minuteswest; // UTC 西偏分鐘
int tz_dsttime; // 夏令時類型
};
#include <sys/time.h> #include <stdio.h> #include <unistd.h>
int main() {
struct timeval tv;
for (int i = 0; i < 4; i++) {
gettimeofday(&tv, NULL);
printf("sec=%ld usec=%ld\n", tv.tv_sec, tv.tv_usec);
sleep(1);
}
return 0;
}
time ./prog > out 查看 real/user/sys。real = user + sys + waitclock_gettime(CLOCK_MONOTONIC, &ts)(納秒級,Linux 專用,不受系統時間調整影響)strftime(fname, sizeof(fname), "log_%Y%m%d_%H%M%S.txt", lt)localtime_r、gmtime_r、ctime_r、asctime_r 接受用戶提供的 struct tm 緩衝區,避免靜態緩衝區競態。