21xrx.com
2024-06-03 04:13:19 Monday
登录
文章检索 我的文章 写文章
如何在C++中获取时间戳
2023-07-05 11:02:30 深夜i     --     --
C++ 时间戳 获取

时间戳是指某个时间点距离某个参考时间的秒数或毫秒数,通常用于记录事件或测量时间间隔。在C++中,获取时间戳的方法有多种。本篇文章将介绍几种获取时间戳的常见方法。

使用time_t获取时间戳:

time_t是一种基本的计时类型,用于存储从1970年1月1日午夜(格林威治时间)到现在的秒数。因此,可以使用time_t来获取当前时间戳。


#include <ctime>

#include <iostream>

int main() {

  time_t now = time(nullptr);

  std::cout << "当前时间戳:" << now << std::endl;

  return 0;

}

运行结果:


当前时间戳:1627587082

使用chrono获取时间戳:

C++11引入的chrono库可以精确计时,可以用它来获取当前时间戳。函数system_clock::now()返回一个std::chrono::time_point对象,可以使用std::chrono::duration_cast将其转换为秒或毫秒数。


#include <chrono>

#include <iostream>

int main() {

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

  auto duration = now.time_since_epoch();

  long long milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();

  std::cout << "当前时间戳:" << milliseconds << std::endl;

  return 0;

}

运行结果:


当前时间戳:1627587082107

使用chrono和strftime获取格式化时间戳:

除了获取时间戳,通常还需要将其转换为友好的日期时间格式。可以使用std::chrono::system_clock::now()获取当前时间,然后使用std::strftime将其转换为指定格式的字符串。需要注意的是,时间戳的单位为秒,需要将其转换为std::tm结构体,再传给std::strftime函数。


#include <chrono>

#include <ctime>

#include <iomanip>

#include <iostream>

int main() {

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

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

  std::tm now_tm = *std::localtime(&now_t);

  char buf[20];

  std::strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", &now_tm);

  std::cout << "当前时间戳:" << buf << std::endl;

  return 0;

}

运行结果:


当前时间戳:2021-07-29 23:58:02

总结:

C++中可以使用time_t、chrono等方法获取时间戳。使用time_t可以获得基本的时间戳,使用chrono可以获得更加精确的时间戳,同时还可以将其转换为友好的日期时间格式。需要根据实际需求选择不同的方法。

  
  

评论区

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