Answer the question
In order to leave comments, you need to log in
Date conversion from char to time_t?
Hello.
There was a need to convert from a char array of the form (dd.mm.yy) to the time_t numerical format (which variable stores seconds from January 1, 1970 to the date we need).
Please let me know how and if it is possible to do this. Assuming that initially in the array the date is correctly described. Or get rid of time_t and replace it with another format, it’s just easier for me to work with it in this case ... it was)
Simply, if you count the seconds of the difference between 1970 and the year declared in the array, then it won’t work correctly, more precisely there will be a lot of checks and extra code, since high years must be taken into account. The same is true for days and months.
Answer the question
In order to leave comments, you need to log in
On the Internet I saw this function: Source
It is not written quite beautifully, but the essence is approximately clear.
The string with the date and time is parsed through sscanf and numbers are extracted from it. If the year is less than 70, then it belongs to the 21st century and you need to add 100 years (because time_t starts on January 1, 1970). Then we write all this into the tm structure and use the mktime function to convert it to time_t. The disadvantage of this method is that it will not work with strings containing a date in an incorrect format.
long CMine::ConvertDateTime(CString buff)
{
int yy, mm, dd, hour, min, sec;
struct tm when;
long tme;
sscanf(buff, "%d/%d/%d %d:%d:%d", &mm, &dd, &yy, &hour, &min, &sec);
if( yy < 70 ) yy+= 100; // year 2000 compliant
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) );
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question