我正在尝试并尝试编写函数来帮助自己轻松转换string
为. 然而,它总是给我错误的一年和错误的时间。怎么了?time_t
time_t
string
我需要它独立于操作系统!
例如,对于 date30/11/2012:09:49:55
它给出30/11/3912:08:49:55
而不是30/11/2012:09:49:55
.
#include <iostream>
#include <string.h>
#include <cstdio>
using namespace std;
time_t string_to_time_t(string s)
{
int yy, mm, dd, hour, min, sec;
struct tm when;
long tme;
memset(&when, 0, sizeof(struct tm));
sscanf(s.c_str(), "%d/%d/%d:%d:%d:%d", &dd, &mm, &yy, &hour, &min, &sec);
time(&tme);
when = *localtime(&tme);
when.tm_year = yy;
when.tm_mon = mm-1;
when.tm_mday = dd;
when.tm_hour = hour;
when.tm_min = min;
when.tm_sec = sec;
return mktime(&when);
}
string time_t_to_string(time_t t)
{
char buff[20];
strftime(buff, 20, "%d/%m/%Y:%H:%M:%S", localtime(&t));
string s(buff);
return s;
}
int main()
{
string s = "30/11/2012:13:49:55";
time_t t = string_to_time_t(s);
string ss = time_t_to_string(t);
cout << ss << "\n";
return 0;
}