VC++ 关于localtime_s简单讲解及使用方法

不知道从vc++哪一个版本开始_s后缀强制要求使用,_s后缀的函数是Windows特有的,_s后缀函数虽然加入了标准库的扩展,还没得到GCC、Clang等编译器的支持,只能在Windows上使用

localtime_sWindows
localtime_rlinux

localtime_s和localtime_r都是只有两个参数,在使用上的区别就是参数位置不同

localtime原型

struct tm *localtime(const time_t * timep);

需要包含#include <time.h>或者#include <ctime>

struct tm的结构为

  int tm_sec;       /* 秒 – 取值区间为[0,60] 包括1闰秒*/
          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()为负。*/

localtime_s原型

struct tm *localtime_r(struct tm *result, const time_t *timep);

localtime_r原型

struct tm *localtime_r(const time_t *timep, struct tm *result);

localtime并不安全

最后附上使用C++编写的关于调用localtime_s获取系统详细日期的代码

#include<iostream>
#include <string>
#include <ctime>

using namespace std;
int main()
{
    struct tm t;   //tm结构指针
    time_t now;  //声明time_t类型变量
    time(&now);      //获取系统日期和时间
    localtime_s(&t, &now);   //获取当地日期和时间

    //格式化输出本地时间
    cout << "年:" << t.tm_year + 1900 << endl;
    cout << "月:" << t.tm_mon + 1 << endl;
    cout << "日:" << t.tm_mday << endl;
    //星期是从星期日开始,星期日是0
    cout << "周:" << t.tm_wday << endl;
    cout << "一年之中:" << t.tm_yday << endl;
    cout << "时:" << t.tm_hour << endl;
    cout << "分:" << t.tm_min << endl;
    cout << "秒:" << t.tm_sec << endl;
    cout << "夏令时:" << t.tm_isdst << endl;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值