【问题标题】:Convert timestamp string to format "%d-%m-%Y"将时间戳字符串转换为格式“%d-%m-%Y”
【发布时间】:2020-12-11 11:52:13
【问题描述】:

我有一个作为 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。

提前致谢!

编辑:这里的 cmets 是我尝试使用 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");

这也不行。

【问题讨论】:

  • 我跟着它并尝试 std::tm tm = *std::localtime(stamp_as_time);和 beauty_date = std::put_time(&tm, "%d");不幸的是,这不起作用
  • time_t 现在通常是 64 位类型,因此您应该改用 stoll

标签: c++ c++11 time stdstring


【解决方案1】:

以下内容应该适合您:

#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 ;
}

DEMO

或者如果你想把它放到beauty_date:

    std::stringstream ss;
    ss << std::put_time(t, "%d-%m-%Y");
    beauty_date = ss.str();

【讨论】:

  • 为什么要从ts_str获取C字串? std::stoi 调用会从中创建另一个 std::stringstd::stoi(ts_str) 就够了。
  • @AsteroidsWithWings 哦,很高兴知道...谢谢
  • @QtFan 不是已经在std:: 中了吗?顺便说一句,如果你喜欢这个答案,请点赞:)
  • @QtFan 你已经够了 :)
猜你喜欢
  • 1970-01-01
  • 2021-03-09
  • 2020-05-09
  • 2021-12-22
  • 1970-01-01
  • 2013-05-05
  • 2023-03-08
  • 1970-01-01
相关资源
最近更新 更多