Linux中的gmtime和localtime,mktime算法

#include<time.h>

time_t time(time_t *calptr) //time函数返回从1970年1月1日的UTC时间的0时0分0秒算起到现在所有的秒数

struct tm *gmtime(const time_t *calptr) //将其转换为标准时间

struct tm *localtime(const time_t *calptr) //将其转换为本地时间

以上两个函数返回一个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代表一月) - 取值区间为[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()为负。*/
long int tm_gmtoff; /*指定了日期变更线东面时区中UTC东部时区正秒数或UTC西部时区的负秒数*/
const char *tm_zone; /*当前时区的名字(与环境变量TZ有关)*/
};

示例代码:
#include<time.h>
#include<stdio.h>

int main(int argc,char **argv)
{
        time_t time_current;
        struct tm * tmp= NULL;

        time_current = time(NULL);
        printf("time_current = %d\n",time_current);

        tmp = gmtime(&time_current);
        printf("gmtime: the time is:\n%d%d%d/%d:%d:%d\n",tmp->tm_year-100+2000,tmp->tm_mon+1,tmp->tm_mday,tmp->tm_hour,tmp- >tm_min,tmp->tm_sec);

        tmp = localtime(&time_current);
        printf("localtime: the time is:\n%d%d%d/%d:%d:%d\n",tmp->tm_year-100+2000,tmp->tm_mon+1,tmp->tm_mday,tmp->tm_hour,tmp- >tm_min,tmp->tm_sec);
    
        return 0;
}
代码运行结果:

Linux源码中的mktime算法
从CMOS中读出来的系统时间并不是time_t类型的,而是类似于struct tm那样,年月日时分秒都是分开存储的。
想要把它转化成系统便于处理的time_t类型,就需要算法进行转换。
Linux的源代码用了短短的几行代码就爱完成了这个复杂的转换(Gauss算法)。
源代码:
include/linux/time.h
static inline unsigned long mktime (unsigned int year, unsigned int mon,
    unsigned int day, unsigned int hour,
    unsigned int min, unsigned int sec)
       {
    if (>= (int) (mon -= 2)){ /**//* 1..12 -> 11,12,1..10 */
         mon += 12; /**//* Puts Feb last since it has leap day */
         year -= 1;
    }
    return (((
             (unsigned long) (year/- year/100 + year/400 + 367*mon/12 + day) +
             year*365 - 719499
          )*24 + hour /**//* now have hours */
       )*60 + min /**//* now have minutes */
    )*60 + sec; /**//* finally seconds */
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值