21xrx.com
2025-04-07 18:52:40 Monday
文章检索 我的文章 写文章
C++获取当前时间:方法和代码示例
2023-07-10 04:04:08 深夜i     53     0
C++ 获取当前时间 方法 代码示例 日期时间函数

在C++编程中,经常需要获取当前时间来进行时间相关的计算和处理,如实现定时器功能、计算时间差等等。本文将介绍在C++中获取当前时间的方法和代码示例。

方法一:使用ctime库

在C++中,可以使用ctime库中的time()函数获取当前系统时间的秒数,并通过gmtime()函数将时间转换为struct tm类型的结构体,最后通过strftime()函数将结构体转换为指定格式的字符串输出。以下是示例代码:

#include <iostream>
#include <cstring>
#include <ctime>
using namespace std;
int main() {
  time_t t = time(NULL);
  struct tm* now = gmtime(&t);
  char buf[80];
  strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", now);
  cout << "Current Time: " << buf << endl;
  return 0;
}

在上述代码中,time(NULL)函数返回当前系统时间的秒数,gmtime()函数将时间转换为struct tm类型的结构体,strftime()函数将结构体转换为指定格式的字符串输出。

方法二:使用chrono库

C++11中新增了chrono库,可以方便地获取当前时间并进行时间计算。以下是示例代码:

#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;
int main() {
  auto now = system_clock::now();
  time_t t = system_clock::to_time_t(now);
  cout << "Current Time: " << ctime(&t);
  return 0;
}

在上述代码中,system_clock::now()函数获取当前时间的duration类型实例,通过system_clock::to_time_t()函数将duration类型转换为time_t类型表示的时间,最后通过ctime()函数将time_t类型的时间转换为字符串输出。

至此,C++获取当前时间的方法和代码示例已经介绍完毕。需要注意的是,获取的时间一般为本地时间,如果需要获取UTC时间,则需要做额外的处理。

  
  

评论区