【发布时间】:2023-03-28 12:40:01
【问题描述】:
Jon Skeet 在 2009 年伦敦 DevDays 上谈到了编程日期和时间的复杂性。
您能给我介绍一下 UNIX 上的 ANSI C 日期/时间函数,并指出在使用日期和时间时我还应该考虑的一些更深层次的问题吗?
【问题讨论】:
Jon Skeet 在 2009 年伦敦 DevDays 上谈到了编程日期和时间的复杂性。
您能给我介绍一下 UNIX 上的 ANSI C 日期/时间函数,并指出在使用日期和时间时我还应该考虑的一些更深层次的问题吗?
【问题讨论】:
日期/时间可以有两种格式:
日期/时间函数和类型在 time.h 头文件中声明。
时间可以存储为整数或结构的实例:
作为使用 time_t 算术类型的数字 - 将日历时间存储为自 UNIX 纪元 1970 年 1 月 1 日 00:00:00 以来经过的秒数
使用结构timeval – 将日历时间存储为自 UNIX 纪元 1970 年 1 月 1 日 00:00:00 以来经过的秒数和纳秒数
使用结构体tm存储本地时间,包含如下属性:
tm_hour
tm_min
tm_isdst
上面的 tm_isdst 属性用于指示夏令时 (DST)。如果值为正则为 DST,如果值为 0 则不是 DST。
#include <stdio.h>
#include <time.h>
int main ( int argc, char *argv[] )
{
time_t now;
now = time ( NULL );
printf ( "It’s %ld seconds since January 1, 1970 00:00:00", (long) now );
return 0;
}
在上面的程序中,函数time 读取 UNIX 系统时间,从 1970 年 1 月 1 日 00:00:00(UNIX 纪元)减去该时间,并以秒为单位返回结果。
#include <stdio.h>
#include <time.h>
int main ( int argc, char *argv[] )
{
time_t now;
struct tm *lcltime;
now = time ( NULL );
lcltime = localtime ( &now );
printf ( "The time is %d:%d\n", lcltime->tm_hour, lcltime->tm_min );
return 0;
}
在上面的程序中,函数 localtime 将 UNIX 纪元的经过时间(以秒为单位)转换为故障时间。 localtime 读取 UNIX 环境 TZ(通过调用 tzset 函数)以返回相对于时区的时间并设置 tm_isdst 属性。
UNIX 中 TZ 变量的典型设置(使用 bash)如下:
export TZ=GMT
或
export TZ=US/Eastern
#include <stdio.h>
#include <time.h>
int main ( int argc, char *argv[] )
{
time_t now;
struct tm *gmt;
char formatted_gmt [50];
now = time ( NULL );
gmt = gmtime ( &now );
strftime ( formatted_gmt, sizeof(formatted_gmt), "%I:%M %p", gmt );
printf ( "The time is %s\n", formatted_gmt );
return 0;
}
在上面的程序中,函数strftime 提供了专门的日期格式。
【讨论】: