使用c++中的strptime将字符串转换为特定的日期时间格式
convert the string to specific datetime format with strptime in c++
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。这里不仅仅是解析和格式化。
相关文章:
- 日期格式为C++
- 如何在QTableView中排序和更改日期格式
- 如何检查日期格式(日/月/年)是否正确C++
- 如何使用put_time()设置日期格式以删除前面的空格和零
- 在 c++ 中验证日期格式
- 使用字符串流设置日期格式
- 日期格式-将日期添加到日期
- 如何在黑莓10中将日期格式转换为字符串
- 提升公历日期格式会产生错误的结果
- Excel 国际日期格式
- 日期格式操作(年/月/日到月/日/年)
- 使用预处理器定义的日期格式
- 将日期格式Www-Mmm-dd hh:mm:ss yyyy转换为c++中的dd hh:mm:ss字符串
- 将字符串设置为日期格式
- 时间刻度到日期格式
- 转换日期格式
- 获取Win32系统日期格式字符串
- 在c++中自定义日期格式
- 如何检查日期格式的有效性(例如,%d/%m/%Y-%H:% m:%S)
- 以字符串形式返回整数值以进行日期格式设置