【发布时间】:2010-09-23 10:19:57
【问题描述】:
我知道这可能很简单,但作为 C++ 我怀疑它会是。如何将 01/01/2008 形式的字符串转换为日期以便我可以操作它?我很高兴将字符串分解为日月年成分。如果解决方案仅适用于 Windows,也很高兴。
【问题讨论】:
我知道这可能很简单,但作为 C++ 我怀疑它会是。如何将 01/01/2008 形式的字符串转换为日期以便我可以操作它?我很高兴将字符串分解为日月年成分。如果解决方案仅适用于 Windows,也很高兴。
【问题讨论】:
#include <time.h>
char *strptime(const char *buf, const char *format, struct tm *tm);
【讨论】:
我没有使用strptime就知道了。
将日期分解为其组成部分,即日、月、年,然后:
struct tm tm;
time_t rawtime;
time ( &rawtime );
tm = *localtime ( &rawtime );
tm.tm_year = year - 1900;
tm.tm_mon = month - 1;
tm.tm_mday = day;
mktime(&tm);
tm 现在可以转换为time_t 并进行操作。
【讨论】:
#include <time.h>
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
int main ()
{
time_t rawtime;
struct tm * timeinfo;
int year, month ,day;
char str[256];
cout << "Inter date: " << endl;
cin.getline(str,sizeof(str));
replace( str, str+strlen(str), '/', ' ' );
istringstream( str ) >> day >> month >> year;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
timeinfo->tm_year = year - 1900;
timeinfo->tm_mon = month - 1;
timeinfo->tm_mday = day;
mktime ( timeinfo );
strftime ( str, sizeof(str), "%A", timeinfo );
cout << str << endl;
system("pause");
return 0;
}
【讨论】:
为什么不使用 boost 寻求更简单的解决方案
using namespace boost::gregorian;
using namespace boost::posix_time;
ptime pt = time_from_string("20150917");
【讨论】:
您可以使用 boost 库(跨平台)
#include <stdio.h>
#include "boost/date_time/posix_time/posix_time.hpp"
int main()
{
std::string strTime = "2007-04-11 06:18:29.000";
std::tm tmTime = boost::posix_time::to_tm(boost::posix_time::time_from_string(strTime));
return 0;
}
但格式应该如前所述:)
【讨论】: