VS2015中控制台程序获取系统时间的方法(2-1)

在VS2015的控制台程序中,可以通过C++标准库函数、Windows API函数和C++11的函数实现。

1 C++标准库函数

通过C++标准库函数time()和localtime_s()获取系统当前时间。

1.1 time()函数

1.1.1 功能

该函数的作用是获取系统当前时间距离1970年1月1日零时的时间,以秒作为单位。

1.1.2 格式

该函数的格式为

time_t time(time_t* time);

其中,参数time是一个指针,获取到的时间就保存到该指针指向的内容中。如果该参数是NULL,则不保存获取到的时间。该函数的返回值即为获取到的时间。time_t是一个long integer类型。

1.2 localtime_s()函数

1.2.1 功能

该函数的功能是将time()函数获取到的秒数转换为当前的年月日时分秒。

1.2.2 格式

该函数的格式为

errno_t localtime_s(struct tm* _tm, const time_t *time);

其中,参数_tm是tm结构的指针,转换后的时间就保存在该指针指向的内容中。

tm的结构定义如下

struct tm

{

    int tm_sec;   // seconds after the minute - [0, 60] including leap second

    int tm_min;   // minutes after the hour - [0, 59]

    int tm_hour;  // hours since midnight - [0, 23]

    int tm_mday;  // day of the month - [1, 31]

    int tm_mon;   // months since January - [0, 11]

    int tm_year;  // years since 1900

    int tm_wday;  // days since Sunday - [0, 6]

    int tm_yday;  // days since January 1 - [0, 365]

    int tm_isdst; // daylight savings time flag

};

该结构中包含了时间信息。参数time是“1.1 time()函数”中获取的时间秒数。如果转换成功,则localtime_s()函数的返回值是0,否则返回错误代码。

1.3 相关代码

获取当前系统时间的代码如下所示

time_t tt = time(NULL);

tm t;

localtime_s(&t, &tt);

printf("%d-%02d-%02d %02d:%02d:%02d",

t.tm_year + 1900, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec);

 

图1 获取系统时间

需要注意的是,使用time()函数与localtime_s()函数,需要添加time.h头文件。

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值