【问题标题】:How do I use the C date and time functions on UNIX?如何在 UNIX 上使用 C 日期和时间函数?
【发布时间】:2023-03-28 12:40:01
【问题描述】:

Jon Skeet 在 2009 年伦敦 DevDays 上谈到了编程日期和时间的复杂性。

您能给我介绍一下 UNIX 上的 ANSI C 日期/时间函数,并指出在使用日期和时间时我还应该考虑的一些更深层次的问题吗?

【问题讨论】:

    标签: c unix datetime date time


    【解决方案1】:

    术语

    日期/时间可以有两种格式:

    • 日历时间(也称为简单时间)- 时间作为绝对值,通常从某个基准时间开始,通常称为协调世界时
    • 本地时间(也称为细分时间)- 由年、月、日等组成的日历时间,其中考虑了当地时区,包括夏令时(如果适用)。

    数据类型

    日期/时间函数和类型在 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 提供了专门的日期格式。

    其他需要考虑的问题

    【讨论】:

    • 值不应该是'TZ=GMT0'(或者,更好的是'TZ=UTC0')吗?我使用后者来运行我的数据库服务器,因此它们运行在一个已知的、可靠的时区(我住在美国/洛杉矶,或者更通俗地说,美国/太平洋时区——尽管我来自 'TZ= GMT0BST' 时区)。
    猜你喜欢
    • 2023-03-06
    • 2011-08-21
    • 2015-10-05
    • 2016-08-19
    • 2022-06-14
    • 2011-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多