M
M
maksqwe2011-04-26 19:19:00
C++ / C#
maksqwe, 2011-04-26 19:19:00

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

2 answer(s)
E
ertaquo, 2011-04-26
@maksqwe

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) );
}

R
Roman, 2011-04-26
@WNeZRoS

You can parse from a string to struct tm(for non-windows systems, there is strptime ), and from tm you can make time_t usingtime_t mktime(struct tm * timeptr)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question