【问题标题】:Convert DDMMMYY[25JUN20] to YYYYMMDD[20200620] in c++在 C++ 中将 DDMMMYY[25JUN20] 转换为 YYYYMMDD[20200620]
【发布时间】:2021-09-14 06:24:08
【问题描述】:

'''

int main()
{
struct std::tm tm;
std::istringstream ss("25JUN20");
ss >> std::get_time(&tm, "%e%b%y"); // or just %T in this case
std::time_t time = mktime(&tm);
std::cout << tm.tm_year << std::endl;

}

'''

我尝试使用此代码,但我的年份出现偏差。 任何帮助将不胜感激。

谢谢

【问题讨论】:

  • std::cout &lt;&lt; tm.tm_year + 1900 &lt;&lt; std::endl;
  • @mediocrevegetable1 我必须将字符串转换为时间格式,这样我才能将其重新生成为我想要的格式。
  • @S.M. 60675957 这是我在 1900 年之后得到的结果,我仍然无法理解它如何等同于 2020
  • @sparshjain 我认为问题在于它无法解析JUN(尽管我不是 100% 确定)。你能做到Jun吗?
  • 你试过struct std::tm tm{};吗?你的语言环境是什么? b 月份,使用区域设置的月份名称。

标签: c++ datetime


【解决方案1】:

即使是对我的问题的更简单的解决方案也会受到赞赏@S.M. – 斯帕什耆那教

使用Howard Hinnant's C++20 chrono preview library(开源,仅标头)非常简单。

#include "date/date.h"
#include <chrono>
#include <iostream>
#include <sstream>

int
main()
{
    std::istringstream ss("25JUN20");
    date::year_month_day ymd;
    ss >> date::parse("%d%b%y", ymd);
    std::cout << date::format("%Y%m%d", ymd) << '\n';
}

输出:

20200625

format 返回一个std::string,所以你可以对这个结果做任何你想做的事情。

我建议使用配置宏ONLY_C_LOCALE=1 进行编译。在 gcc 和 clang 上,这最容易在命令行上使用 -DONLY_C_LOCALE=1 完成。使用 VS 可以在 IDE 中设置宏。

我推荐这个宏的原因是 gcc 和 VS std 库通常不会以不区分大小写的方式解析月份名称,ONLY_C_LOCALE=1 告诉 date.h 解决该错误。如果您使用的是 LLVM 的 libc++,则不需要此解决方法。

此代码将移植到 C++20,只需进行一些小改动:

#include <chrono>
#include <format>
#include <iostream>
#include <sstream>

int
main()
{
    std::istringstream ss("25JUN20");
    std::chrono::year_month_day ymd;
    ss >> std::chrono::parse("%d%b%y", ymd);
    std::cout << std::format("{:%Y%m%d}", ymd) << '\n';
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-22
    • 2015-12-11
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多