C++中获取当前时间并格式化输出

本文介绍了一种使用C++获取当前时间并将其格式化为字符串的方法。通过调用time.h库中的函数,可以将时间戳转换为本地时间,并进一步转化为YYYY-MM-DD HH:MM:SS格式的字符串。
 1 #include <string>
 2 #include <time.h>
 3 using namespace std;
 4 
 5 string getTime()
 6 {
 7     time_t timep;
 8     time (&timep);
 9     char tmp[64];
10     strftime(tmp, sizeof(tmp), "%Y-%m-%d %H:%M:%S",localtime(&timep) );
11     return tmp;
12 }
13 
14 int main(){
15     string   time = getTime();
16     cout << time << endl;
17 
18     return 0;
19 }

输出结果为:

转载于:https://www.cnblogs.com/danielStudy/p/6762107.html

C++获取当前时间格式化输出(精确到毫秒)可以使用 `<chrono>` 和 `<iomanip>` 库结合实现。`<chrono>` 提供了对时间点和持续时间的操作,而 `<iomanip>` 则用于格式化输出。 以下是一个完整的示例代码,展示了如何获取当前系统时间以 `YYYY-MM-DD HH:MM:SS.mmm` 的格式输出: ```cpp #include <iostream> #include <chrono> #include <iomanip> #include <sstream> std::string getCurrentTimeWithMilliseconds() { // 获取当前时间点 auto now = std::chrono::system_clock::now(); // 转换为时间戳 auto now_time_t = std::chrono::system_clock::to_time_t(now); // 获取毫秒部分 auto milliseconds = std::chrono::duration_cast<std::chrono::milliseconds>( now.time_since_epoch() ).count() % 1000; // 将时间转换为tm结构体 tm local_tm; #ifdef _WIN32 localtime_s(&local_tm, &now_time_t); // Windows平台 #else localtime_r(&now_time_t, &local_tm); // Linux/Unix平台 #endif // 使用stringstream进行格式化输出 std::stringstream ss; ss << std::put_time(&local_tm, "%Y-%m-%d %H:%M:%S"); ss << "." << std::setw(3) << std::setfill('0') << milliseconds; return ss.str(); } int main() { std::string formatted_time = getCurrentTimeWithMilliseconds(); std::cout << "Current time with milliseconds: " << formatted_time << std::endl; return 0; } ``` ### 输出示例: ``` Current time with milliseconds: 2025-04-05 12:34:56.789 ``` ### 关键点说明: - 使用 `std::chrono::system_clock::now()` 获取当前时间点。 - 使用 `std::chrono::duration_cast` 提取毫秒部分。 - 使用 `std::put_time` 格式化日期和时间部分。 - 使用 `std::stringstream` 拼接毫秒确保三位数补零。 该方法适用于 C++11 及以上标准,支持跨平台编译(Windows/Linux/Unix)。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值