在线代码实验室
实测 <time.h> 的 struct tm/mktime/strftime、gmtime/difftime/asctime 与 C11 timespec_get
#include <stdio.h>
#include <time.h>
#include <string.h>
#include <stdbool.h>
int main(void) {
struct tm custom = {0};
custom.tm_year = 2024 - 1900;
custom.tm_mon = 5;
custom.tm_mday = 12;
custom.tm_hour = 12;
custom.tm_min = 0;
custom.tm_sec = 0;
custom.tm_isdst = -1;
time_t mk = mktime(&custom);
char formatted[64] = {0};
size_t flen = strftime(formatted, sizeof(formatted), "%Y-%m-%d %H:%M:%S", &custom);
bool c1_pass = (mk != (time_t)-1 && flen == 19 && strcmp(formatted, "2024-06-12 12:00:00") == 0 && custom.tm_wday == 3);
time_t t0 = 0;
time_t t1 = 86400;
double diff_sec = difftime(t1, t0);
struct tm *utc0 = gmtime(&t0);
int utc_ok = (utc0 != NULL && utc0->tm_year == 70 && utc0->tm_mon == 0 && utc0->tm_mday == 1 && utc0->tm_hour == 0) ? 1 : 0;
const char *asc = (utc0 != NULL) ? asctime(utc0) : "";
int asc_ok = (strncmp(asc, "Thu Jan 1 00:00:00 1970", 24) == 0) ? 1 : 0;
bool c2_pass = (diff_sec == 86400.0 && utc_ok == 1 && asc_ok == 1);
time_t now = time(NULL);
const char *ct = ctime(&now);
clock_t clk = clock();
struct timespec ts = {0, 0};
int ts_base = timespec_get(&ts, TIME_UTC);
int now_ok = (now > 0 && ct != NULL && strlen(ct) >= 24) ? 1 : 0;
int clk_ok = (clk != (clock_t)-1 && CLOCKS_PER_SEC > 0) ? 1 : 0;
int ts_ok = (ts_base == TIME_UTC && ts.tv_sec > 0 && ts.tv_nsec >= 0 && ts.tv_nsec < 1000000000L) ? 1 : 0;
bool c3_pass = (now_ok == 1 && clk_ok == 1 && ts_ok == 1);
printf(
"{"
"\"runtime\":\"GCC C11 (mstorsjo/llvm-mingw:20260616)\","
"\"cases\":["
"{\"name\":\"struct_tm_mktime_strftime\",\"expected\":\"2024-06-12 12:00:00,wday=3\",\"actual\":\"%s,wday=%d\",\"passed\":%s},"
"{\"name\":\"gmtime_difftime_asctime\",\"expected\":\"diff=86400,utc=1,asc=1\",\"actual\":\"diff=%.0f,utc=%d,asc=%d\",\"passed\":%s},"
"{\"name\":\"time_clock_and_timespec_get\",\"expected\":\"now=1,clk=1,ts=1\",\"actual\":\"now=%d,clk=%d,ts=%d\",\"passed\":%s}"
"]"
"}\n",
formatted, custom.tm_wday, c1_pass ? "true" : "false",
diff_sec, utc_ok, asc_ok, c2_pass ? "true" : "false",
now_ok, clk_ok, ts_ok, c3_pass ? "true" : "false"
);
return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。
入口文件:projects/c-standard-library-time-h-lab/explore-standard-library-time-h.c
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-standard-library-time-h.c,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3260.zip
课程关联工程包(登记关联63章) · 含当前章节或实例 · mbskycom202612a3210.zip