首页 > 解决方案 > 将时间戳字符串转换为格式“%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");

这也不行。

标签: c++c++11timestdstring

解决方案


以下应该为您工作:

#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();

推荐阅读