使用<chrono>库获取当前时间,通过std::chrono::system_clock::now()得到时间点,转换为std::time_t后用std::localtime或std::gmtime转为std::tm结构,再结合std::put_time格式化输出;推荐std::put_time进行安全、现代的流式格式化,而时区处理在C++20前建议统一使用UTC时间并借助std::gmtime,复杂场景可引入第三方库如Howard Hinnant的date库;日期时间计算利用duration与time_point支持加减和比较操作,实现高精度且类型安全的时间间隔测量与逻辑判断。

在C++中获取当前日期和时间,通常我们会依赖两个核心库:现代C++推崇的
<chrono>
<ctime>
<chrono>
<ctime>
要获取当前日期和时间,最直接的方法是利用
std::chrono::system_clock::now()
time_point
time_point
一个常见的流程是将
std::chrono::system_clock::now()
time_point
std::time_t
std::time_t
std::time_t
std::localtime
std::gmtime
std::tm
std::tm
#include <iostream>
#include <chrono>
#include <ctime> // for std::time_t, std::tm, std::localtime, std::mktime, std::put_time
int main() {
// 1. 获取当前时间点
auto now = std::chrono::system_clock::now();
// 2. 将时间点转换为std::time_t
// 注意:system_clock的time_point可以直接转换为time_t
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
// 3. 将std::time_t转换为本地时间结构体std::tm
// std::localtime返回的指针指向一个静态分配的tm对象,非线程安全
// 更好的做法是使用可重入版本,如localtime_r (POSIX) 或手动复制
// 这里为演示目的,简化处理
std::tm* local_tm = std::localtime(&now_c);
// 4. 使用std::put_time进行格式化输出 (C++11)
if (local_tm) { // 检查指针是否有效
std::cout << "当前本地日期和时间 (C++11 chrono + put_time): ";
std::cout << std::put_time(local_tm, "%Y-%m-%d %H:%M:%S") << std::endl;
} else {
std::cerr << "获取本地时间失败。" << std::endl;
}
// 另一种获取UTC时间的方式
std::tm* gmt_tm = std::gmtime(&now_c);
if (gmt_tm) {
std::cout << "当前UTC日期和时间 (C++11 chrono + put_time): ";
std::cout << std::put_time(gmt_tm, "%Y-%m-%d %H:%M:%S UTC") << std::endl;
} else {
std::cerr << "获取UTC时间失败。" << std::endl;
}
// 传统C风格的ctime库用法(仅作对比,不推荐新项目使用)
// std::time_t rawtime;
// std::time(&rawtime); // 获取当前时间戳
// std::tm* info = std::localtime(&rawtime); // 转换为本地时间结构体
// char buffer[80];
// std::strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M:%S", info);
// std::cout << "当前本地日期和时间 (C风格 ctime): " << buffer << std::endl;
return 0;
}这段代码展示了如何利用
<chrono>
<ctime>
std::localtime
std::gmtime
localtime_r
std::tm
立即学习“C++免费学习笔记(深入)”;
对日期时间进行格式化输出是日常开发中一个非常普遍的需求。C++标准库主要提供了两种方式来精细控制输出格式:
std::put_time
std::strftime
std::tm
std::put_time
<iomanip>
std::cout
std::tm
std::strftime
以下是一些常用的格式化指令:
%Y
%m
%d
%H
%m
%S
%w
%a
%a
%b
%b
%c
%x
%x
例如,如果你想输出"YYYY年MM月DD日 HH时MM分SS秒",你可以这样做:
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip> // for std::put_time
int main() {
auto now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::tm* local_tm = std::localtime(&now_c);
if (local_tm) {
// 使用put_time进行多种格式化输出
std::cout << "格式1 (YYYY-MM-DD HH:MM:SS): "
<< std::put_time(local_tm, "%Y-%m-%d %H:%M:%S") << std::endl;
std::cout << "格式2 (MM/DD/YY hh:mm AM/PM): "
<< std::put_time(local_tm, "%m/%d/%y %I:%M %p") << std::endl;
std::cout << "格式3 (完整日期时间,包含星期): "
<< std::put_time(local_tm, "%A, %B %d, %Y %H:%M:%S") << std::endl;
// 使用strftime (需要缓冲区)
char buffer[100];
if (std::strftime(buffer, sizeof(buffer), "今天是 %Y年%m月%d日,现在是 %H时%M分%S秒", local_tm)) {
std::cout << "strftime输出: " << buffer << std::endl;
} else {
std::cerr << "strftime格式化失败。" << std::endl;
}
}
return 0;
}选择
std::put_time
std::strftime
std::put_time
在处理日期和时间时,时区是一个绕不开的复杂问题。不同地区有不同的本地时间,而UTC(Coordinated Universal Time,协调世界时)则提供了一个全球统一的时间基准,不随地理位置或季节变化。在跨区域、分布式系统或需要精确时间同步的场景中,使用UTC时间作为内部存储和传输的标准是最佳实践。
C++标准库在C++20之前对时区的原生支持是比较有限的,主要通过
std::gmtime
std::tm
std::localtime
std::tm
std::gmtime
std::time_t
std::tm
std::localtime
要获取当前的UTC时间,你可以直接将
std::chrono::system_clock::now()
std::time_t
std::gmtime
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
int main() {
auto now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
// 获取UTC时间
std::tm* gmt_tm = std::gmtime(&now_c);
if (gmt_tm) {
std::cout << "当前UTC时间: " << std::put_time(gmt_tm, "%Y-%m-%d %H:%M:%S UTC") << std::endl;
} else {
std::cerr << "获取UTC时间失败。" << std::endl;
}
// 获取本地时间
std::tm* local_tm = std::localtime(&now_c);
if (local_tm) {
std::cout << "当前本地时间: " << std::put_time(local_tm, "%Y-%m-%d %H:%M:%S %Z") << std::endl;
// %Z 可以尝试输出时区名称,但其支持依赖于具体实现和系统设置
} else {
std::cerr << "获取本地时间失败。" << std::endl;
}
return 0;
}在C++20中,
<chrono>
std::chrono::utc_clock
std::chrono::tai_clock
std::chrono::utc_clock::now()
zoned_time
time_zone
对于C++17及更早的版本,如果需要更复杂的时区处理(例如,跨时区转换、夏令时规则),你可能需要考虑使用第三方库,例如Howard Hinnant的
date
<chrono>
日期和时间的计算与比较是另一个高频需求,例如计算事件持续时间、判断某个时间点是否在特定区间内、或者在当前时间基础上增加/减少一段时间。C++的
<chrono>
duration
time_point
std::chrono::duration
std::chrono::seconds
std::chrono::milliseconds
std::chrono::time_point
system_clock
duration
1. 计算时间间隔(Duration): 你可以通过两个
time_point
duration
#include <iostream>
#include <chrono>
#include <thread> // for std::this_thread::sleep_for
int main() {
auto start = std::chrono::high_resolution_clock::now(); // 更高精度时钟
// 模拟一些工作
std::this_thread::sleep_for(std::chrono::milliseconds(1234));
auto end = std::chrono::high_resolution_clock::now();
// 计算持续时间
auto duration = end - start;
// 将持续时间转换为不同的单位
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(duration).count();
auto s = std::chrono::duration_cast<std::chrono::seconds>(duration).count();
std::cout << "操作耗时: " << ms << " 毫秒" << std::endl;
std::cout << "操作耗时: " << s << " 秒" << std::endl; // 会向下取整
// 也可以直接输出 duration 对象 (C++20)
// std::cout << "精确耗时: " << duration << std::endl;
// 对于C++17及之前,需要手动格式化
std::cout << "精确耗时 (微秒): " << std::chrono::duration_cast<std::chrono::microseconds>(duration).count() << " 微秒" << std::endl;
return 0;
}2. 日期时间加减(Adding/Subtracting Durations):
time_point
duration
time_point
#include <iostream>
#include <chrono>
#include <ctime>
#include <iomanip>
int main() {
auto now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::tm* local_tm = std::localtime(&now_c);
if (local_tm) {
std::cout << "当前时间: " << std::put_time(local_tm, "%Y-%m-%d %H:%M:%S") << std::endl;
}
// 在当前时间基础上增加1小时30分钟
auto future_time = now + std::chrono::hours(1) + std::chrono::minutes(30);
std::time_t future_c = std::chrono::system_clock::to_time_t(future_time);
std::tm* future_tm = std::localtime(&future_c);
if (future_tm) {
std::cout << "1小时30分钟后: " << std::put_time(future_tm, "%Y-%m-%d %H:%M:%S") << std::endl;
}
// 减少2天
auto past_time = now - std::chrono::days(2); // C++20 才有 std::chrono::days
// 对于C++17及之前,需要转换为小时或秒:
// auto past_time = now - std::chrono::hours(2 * 24);
std::time_t past_c = std::chrono::system_clock::to_time_t(past_time);
std::tm* past_tm = std::localtime(&past_c);
if (past_tm) {
std::cout << "2天前: " << std::put_time(past_tm, "%Y-%m-%d %H:%M:%S") << std::endl;
}
return 0;
}注意:
std::chrono::days
std::chrono::weeks
2 * 24 * std::chrono::hours(1)
2 * 24 * 60 * 60 * std::chrono::seconds(1)
3. 日期时间比较:
time_point
==
!=
<
>
<=
>=
#include <iostream>
#include <chrono>
#include <thread>
int main() {
auto time1 = std::chrono::system_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(1));
auto time2 = std::chrono::system_clock::now();
std::this_thread::sleep_for(std::chrono::seconds(1));
auto time3 = std::chrono::system_clock::now();
if (time1 < time2) {
std::cout << "time1 在 time2 之前" << std::endl;
}
if (time2 == time2) { // 显然
std::cout << "time2 等于 time2" << std::endl;
}
if (time3 > time1) {
std::cout << "time3 在 time1 之后" << std::endl;
}
// 判断某个时间点是否在特定区间内
auto specific_point = time1 + std::chrono::milliseconds(500);
if (specific_point > time1 && specific_point < time2) {
std::cout << "特定时间点在 time1 和 time2 之间" << std::endl;
}
return 0;
}通过这些
chrono
time_t
tm
以上就是如何在C++中获取当前日期和时间_C++日期时间库使用详解的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号