21xrx.com
2024-06-03 09:01:56 Monday
登录
文章检索 我的文章 写文章
C++输出当前时间的方法
2023-07-07 10:26:36 深夜i     --     --
C++ 输出 当前时间 方法

在C++中,要输出当前时间可以用系统函数time和localtime来实现。以下是实现方法:

首先需要包含ctime头文件:


#include <ctime>

接下来,定义函数:


void showCurrentTime()

{

 time_t now = time(0);

 struct tm tstruct;

 char currentTime[80];

 tstruct = *localtime(&now);

 strftime(currentTime, sizeof(currentTime), "%Y-%m-%d %X", &tstruct);

 std::cout << currentTime << std::endl;

}

在这个函数中,我们首先使用time(0)函数获取当前时间的时间戳,然后使用localtime转换成本地时间。最后,我们使用strftime函数将时间转换为指定格式的字符串,%Y代表年份,%m代表月份,%d代表日期,%X代表时间,最后将这个字符串输出。

通过调用这个函数showCurrentTime(),便可以输出当前时间了。

在使用这个函数时,还需要注意一些要点。比如要包含iostream头文件,time_t类型的now需初始化为time(0),而strftime函数的第三个参数为转换后的时间结构体。

总的来说,在C++中输出当前时间的方法还是比较简单的,只需使用几个系统函数就能轻松实现。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复