Jan 26, 2016 at 4:04pm Jan 26, 2016 at 4:04pm UTC
This is my attempt:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <time.h>
#include <string>
#include <iostream>
#include <stdio.h>
#include <conio.h>
#include <Windows.h>
long gettimezone(){
TIME_ZONE_INFORMATION tzinfo;
GetTimeZoneInformation(&tzinfo);
return tzinfo.Bias;
}
unsigned long tsfstr(std::string datetime="1970.01.01 00:00:00" ){
if (datetime.length()<19){std::cout<<"invalid string - cant convert to timestamp" ; _getch();}
struct tm tm;
tm.tm_year=atoi(datetime.substr(0,4).c_str())-1900;
tm.tm_mon=atoi(datetime.substr(5, 2).c_str())-1;
tm.tm_mday=atoi(datetime.substr(8, 2).c_str());
tm.tm_hour=atoi(datetime.substr(11, 2).c_str());
tm.tm_min=atoi(datetime.substr(14, 2).c_str());
tm.tm_sec=atoi(datetime.substr(17, 2).c_str());
char buff[80];
strftime(buff, 80, "%Y.%m.%d %H:%M:%S" , &tm);
std::cout<<"should be: " <<std::string(buff)<<"\n" ;
return mktime(&tm);
}
int main(){
std::cout<<tsfstr("2010.01.31 00:00:00" );
_getch();
}
Output:
should be: 2010.01.31 00:00:00
1264910400
Apparently 1264910400 is 2010.01.31 04:00:00 UTC though
Last edited on Jan 26, 2016 at 4:05pm Jan 26, 2016 at 4:05pm UTC
Jan 26, 2016 at 5:01pm Jan 26, 2016 at 5:01pm UTC
Do you have a question or problem?
Jan 26, 2016 at 5:13pm Jan 26, 2016 at 5:13pm UTC
Well, I was expecting 1264896000 / 2010.01.31 00:00:00 UTC. Where's the error in my conversion?
Jan 29, 2016 at 2:03pm Jan 29, 2016 at 2:03pm UTC
i thought time_t was typedef'd as unsigned long
easier fix: use _mkgmtime()
Jan 29, 2016 at 3:42pm Jan 29, 2016 at 3:42pm UTC
i thought time_t was typedef'd as unsigned long
Not necessarily, time_t is in implementation defined unsigned type. While it "could" an unsigned long or it "could" just as well be an unsigned int or an unsigned long long, it depends on the implementation. You should always try to use the correct type, since mktime() returns a time_t, you should use a time_t.
Edit:
easier fix: use _mkgmtime()
That may be fine, just realize that that function is not a standard C or C++ function, it is an implementation defined function that may not be available with all compilers.
Last edited on Jan 29, 2016 at 4:04pm Jan 29, 2016 at 4:04pm UTC