使用c++中的strptime将字符串转换为特定的日期时间格式

convert the string to specific datetime format with strptime in c++

本文关键字:日期 格式 时间 转换 中的 c++ strptime 字符串 使用      更新时间:2023-10-16
        I have a string in format Date Time 20160524T154628
        Now want the values in terms::hr :: 15,mm:: 46,ss :: 28,month:: 05,year:: 2016,day:: 24
 string convertstring(*str1)
    {
         struct tm t;
          strptime(sr1, "%Y%m%dT%H%M%S", &t);
        char buffer[256];
          strftime(buffer, sizeof(buffer), "%F %T", &t);
    string str2(buffer);
    return str2;
    }

使用这个现代的(c++ 11/14),免费开源日期/时间/时区库:

#include "tz.h"
#include <iostream>
#include <sstream>
#include <stdexcept>
std::string
convertstring(const std::string& str1)
{
    std::istringstream buf{str1};
    date::local_seconds t;
    date::parse(buf, "%Y%m%dT%H%M%S", t);
    if (buf.fail())
        throw std::runtime_error("Could not parse " + str1);
    return date::format("%F %T", t);
}
int
main()
{
    std::cout << convertstring("20160524T154628") << 'n';
}
输出:

2016-05-24 15:46:28

现在你可以用一个现代的c++ API来处理日期/时间,而不是用一个古老的C API。这里不仅仅是解析和格式化。