CPP -- 获取系统时间

使用函数time()获取系统时间(UTC),其声明为:

   time_t time(time_t * t); // 其中,time_t为long;形参可以为NULL

 

1)返回自1970年1月1日00:00:00至当前的秒数,通过计算转为相应的时分秒:

    time_t t_cur = {0};

   time(&t_cur);

   long sod = t_cur % (3600*24);

   int hh = sod / 3600;

   long moh = sod % 3600;

   int mm = moh / 3600;

    int ss = moh % 60;

    printf("current time is: d:dd\n", hh, mm, ss);

 

2)借助struct tm转为年月日时分秒:

    time_t t_cur;
    time(&t_cur); // UTC时间
    struct tm *p = gmtime(&t_cur);
    printf("UTC is: M/d/d d:d:d\n", 1900+p->tm_year, 1+p->tm_mon,

              p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);

    p = localtime(&t_cur); // 转为当前时区时间
    printf("UTC+8 is: M/d/d d:d:d\n", 1900+p->tm_year, 1+p->tm_mon,

             p->tm_mday, p->tm_hour, p->tm_min, p->tm_sec);

// struct tm中:tm_year为自1900起的年数;tm_mon为自一月起的月数,取值[0,11];tm_sec为int类型;tm_wday为自周日的天数,取值[0,6];其他按惯例。

 

3)struct tm转为time_t,使用mktime(),其声明如下:

    time_t mktime(struct tm * _Tm);  // 若用户输入的日期时间有误,则函数返回值为-1;使用时注意上文中红色提示。

 

4)使用asctime()获取形如 Sun Sep 07 16:25:00 2014 字符串,函数声明为:

    char * asctime(const struct tm * _Tm);

 

5)使用ctime()获取形如 Sun Sep 07 16:25:00 2014 字符串,函数声明为:

    char * ctime(const time_t * _Time);

 

PS: 整理自:http://www.eefocus.com/xuefu2009/blog/

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值