Linux系统时间 time.h 之 函数gmtime使用

本文介绍了C语言中的gmtime函数用于将UTC秒数转换为tm结构体,并讨论了gmtime_s的安全版本。同时,讲述了asctime函数如何将tm结构体转换为文本时间格式。通过实例演示了如何在多线程环境下安全使用这些函数。
摘要由CSDN通过智能技术生成
/*
UTC秒数转日历时间-gmtime函数 是int类型的结构体 返回tm 
struct tm *gmtime(const time_t *timer);
struct tm *gmtime_r (const time_t *timer,struct tm *buf);
    
struct tm *gmtime_s (const time_t *限制时间,struct tm *限制结果);
与所有边界检查的函数一样,gmtime_s只有__STDC_LIB_EXT1__在实现定义并且用户在包含之前定义__STDC_WANT_LIB_EXT1__为整数常量时1才能保证可用time.h。
    
gmtime 将结果转化为真实世界的时间并保存在静态变量里,然后放回一个指向该变量的指针。该函数线程不安全,localtime、ctime都可以使用该指针
gmtime_r / gmtime_s 将结果保存在buf中。 因此在多线程开发中可以安全应用 
    
*/
//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代表一月) - 取值区间为[0,11] */
//    int tm_year;      /* 年份,其值等于实际年份减去1900 */
//    int tm_wday;      /* 星期 – 取值区间为[0,6],其中0代表星期天,1代表星期一,以此类推 */
//    int tm_yday;      /* 从每年的1月1日开始的天数 – 取值区间为[0,365],其中0代表1月1日,1代表1月2日,以此类推 */
//    int tm_isdst;     /* 夏令时标识符,实行夏令时的时候,tm_isdst为正。不实行夏令时的进候,tm_isdst为0;不了解情况时,tm_isdst()为负。*/
//    };

/*
浅谈asctime函数
asctime 可将tm的日历时间转化为文本格式的时间字符串,固定为25个字符,考虑到还有个\0,所以是26个字符 
Www Mmm dd hh:mm:ss yyyy
*/
#define __STDC_WANT_LIB_EXT1__ 1
#define _XOPEN_SOURCE // for putenv
#include <time.h>
#include <stdio.h>
#include <stdlib.h>   // for putenv
/*int main(void)
{
    time_t t = time(NULL); //将1970-1-1至今的秒数转化为string 写入t 
    printf("UTC:       %s", asctime(gmtime(&t)));
    printf("local:     %s", asctime(localtime(&t)));
    // POSIX-specific
    putenv("TZ=Asia/Singapore");
    printf("Singapore: %s", asctime(localtime(&t)));
 
#ifdef __STDC_LIB_EXT1__
    struct tm buf;
    char str[26];
    asctime_s(str,sizeof str,gmtime_s(&t, &buf));
    printf("UTC:   %s", str);
    asctime_s(str,sizeof str,localtime_s(&t, &buf));
    printf("local: %s", str);
#endif
}*/ 
void main ()
{
    time_t t = time(NULL);
    printf("%s\n",asctime(gmtime(&t)));//将gmtime中tm描述的日历时间转化为文本格式 
    printf("%d\n",gmtime(&t));
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值