21xrx.com
2024-09-19 09:39:49 Thursday
登录
文章检索 我的文章 写文章
C++如何获取当前时间字符串?
2023-06-24 13:52:33 深夜i     --     --
C++ 获取 当前时间 字符串

C++作为一门热门的编程语言,在日常开发中经常需要获取当前时间字符串以便进行记录、统计、比较等操作。接下来我们将介绍如何在C++中获取当前时间字符串。

C++中获取当前时间的方法有两种,一种是使用ctime库,另一种是使用chrono库。

ctime库主要提供了两个获取当前时间的函数:time和localtime。time函数可以获取当前时间的秒数,而localtime函数可以将秒数转换成struct tm类型的本地时间,然后再进行格式化输出。

下面是一个使用ctime库获取当前时间字符串的例子:


#include <iostream>

#include <ctime>

int main() {

 // 获取当前时间的秒数

 std::time_t now = std::time(nullptr);

 // 将秒数转换成struct tm类型的本地时间

 std::tm* local = std::localtime(&now);

 // 格式化输出

 char buffer[80];

 std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", local);

 std::cout << buffer << std::endl;

 return 0;

}

上述代码中,使用time函数获取当前时间的秒数,然后使用localtime函数将秒数转换成本地时间。最后使用strftime函数将本地时间格式化成字符串并输出。

另一种获取当前时间的方法是使用chrono库。chrono库提供了一些高精度的时间类型和操作函数,可以更加方便地进行时间计算和转换。下面是一个使用chrono库获取当前时间字符串的例子:


#include <iostream>

#include <chrono>

#include <iomanip>

int main() {

 // 获取当前时间的高精度表示

 auto now = std::chrono::system_clock::now();

 // 转换成time_t类型

 std::time_t t = std::chrono::system_clock::to_time_t(now);

 // 格式化输出

 std::cout << std::put_time(std::localtime(&t), "%Y-%m-%d %H:%M:%S") << std::endl;

 return 0;

}

上述代码中,使用system_clock::now函数获取当前时间的高精度表示,然后使用to_time_t函数转换成time_t类型的本地时间。最后使用put_time函数将本地时间格式化成字符串并输出。

综上所述,C++中获取当前时间字符串的方法较为简单,开发者可以根据自身需要选择更加方便和高效的方法来实现。

  
  

评论区

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