c++ - 将时间戳字符串转换为格式“%d-%m-%Y”
问题描述
我有一个作为 std::string 的 unix 时间戳,我想将它转换为一个漂亮的日期字符串。已经提出的问题仅显示获取当前时间的转换(并在所有地方使用“自动”,所以我不确定哪个类是合适的)但这是一个已经存在的 std::string。
std::string beauty_date; //"%d-%m-%Y"
std::string stamp = "1567555200";
time_t stamp_as_time = (time_t) std::stoi(stamp);
我想这需要首先转换为无符号长整数(又名 time_t)。我的问题是如何将“stamp_as_time”放入beauty_date。
提前致谢!
编辑:从这里的评论是我尝试使用 put_time
std::string beauty_date; //"%d-%m-%Y"
std::string stamp = "1567555200";
time_t stamp_as_time = (time_t) std::stoi(stamp);
beauty_date = std::put_time(std::localtime(&stamp_as_time), "%d-%m-%Y");
这也不行。
解决方案
以下应该为您工作:
#include<iostream>
#include<iomanip>
#include<string>
#include<ctime>
int main() {
std::string ts_str{ "1567555200" };
std::int64_t result = std::stoi(ts_str);
std::time_t tmp = result;
std::tm* t = std::gmtime(&tmp);
std::cout << std::put_time(t, "%d-%m-%Y") << std::endl;
return 0 ;
}
或者,如果您想将其放入beauty_date
:
std::stringstream ss;
ss << std::put_time(t, "%d-%m-%Y");
beauty_date = ss.str();
推荐阅读
- .net - Azure Batch Pool 下的 RelativeMountPath
- ssl - 使用自签名证书时无法将 arduino mkr1000 与 mosquitto 代理连接
- c# - 执行 BlobClient.UploadAsync 时出现 HttpRequestException
- node.js - Google App Engine 实例 - 我的代码可以确定实例数据吗?
- c++ - 尝试关闭 DesktopWindowXamlSource 时抛出异常
- python - 如何在 tkinter 中将 sqlite3 数据库导出为 csv?
- html - SVG/D3 - 嵌入 svg 图像的 g 未显示(g 大小为 0 x 0,svg 图像无处可见)
- python - 使用没有序列化错误的日期时间对象记录字典
- python - seaborn gridplot/subplots 在第一列显示一个变量,在第二列显示同一行 ID 的另一个变量
- c++ - c++ makefile 未检测到 .h 文件中的更改