在 Linux 中,C++ 可以使用 <chrono> 库和 <ctime> 库来进行时间处理。下面是一些常用的方法:
- 使用
<chrono>库(C++11 及更高版本)
<chrono> 库提供了高精度的时间处理功能。以下是一些示例:
#include <iostream>
#include <chrono>
int main() {
// 获取当前时间点
auto now = std::chrono::system_clock::now();
// 将时间点转换为时间戳(毫秒)
auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
std::cout << "Current time in milliseconds: " << now_ms << std::endl;
// 将时间戳(毫秒)转换为时间点
auto ms = std::chrono::milliseconds(now_ms);
auto past = now - ms;
std::cout << "1 second ago: " << std::chrono::system_clock::to_time_t(past) << std::endl;
return 0;
}
- 使用
<ctime>库
<ctime> 库提供了 C 风格的时间处理功能。以下是一些示例:
#include <iostream>
#include <ctime>
int main() {
// 获取当前时间
std::time_t now = std::time(nullptr);
std::cout << "Current time: " << std::ctime(&now);
// 将时间戳转换为本地时间结构体
std::tm *local_time = std::localtime(&now);
std::cout << "Local time: " << std::asctime(local_time);
// 将本地时间结构体转换为时间戳
std::time_t local_time_ts = std::mktime(local_time);
std::cout << "Local time in seconds since epoch: " << local_time_ts << std::endl;
return 0;
}
注意:在使用 <ctime> 库时,需要注意时区问题。std::localtime() 函数会根据系统设置返回本地时间,而 std::gmtime() 函数会返回 UTC 时间。在进行时间计算时,建议使用 UTC 时间以避免时区问题。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1486471.html