21xrx.com
2025-07-13 10:00:07 Sunday
登录
文章检索 我的文章 写文章
C++如何输出时间?
2023-06-27 08:05:21 深夜i     37     0
C++ 输出 时间

C++可以使用time库来输出时间。time库是C++标准库的一部分,它包含了一些与时间相关的函数和结构体,可以方便地获取和操作时间数据。

要输出当前时间,可以使用time函数。time函数用于获取从1970年1月1日到当前时间所经过的秒数。代码如下:

#include <iostream>
#include <ctime>
int main()
{
  time_t now = time(0);
  std::cout << now << std::endl;
  return 0;
}

运行结果为当前时间距离1970年1月1日的秒数。

如果需要将时间格式化输出,可以使用strftime函数。strftime函数可以将时间转换为指定的格式,并输出到指定的字符串中。代码如下:

#include <iostream>
#include <ctime>
int main()
{
  time_t now = time(0);
  struct tm* t = localtime(&now);
  char buffer[80];
  strftime(buffer, 80, "%Y-%m-%d %H:%M:%S", t);
  std::cout << buffer << std::endl;
  return 0;
}

运行结果为当前日期和时间,格式为“年-月-日 时:分:秒”。

除了strftime函数,C++还提供了一些其它的时间处理函数,如gmtime函数和mktime函数。这些函数可以用于将时间从一种格式转换为另一种格式,或对时间进行加减运算等操作。因此,使用C++输出时间可以非常灵活和方便。

  
  

评论区