Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing yyyy-MM-dd HH:mm:ss date time string?

Tags:

c++

I have a date time that comes from mysql. I need to extract each part:

int year;
int month;
int day;
int hour;
int min;
int sec;

example:

2014-06-10 20:05:57

Is there a simpler way than running it through stringstream for each component? (no boost or c++11 solutions please).

Thanks

like image 530
jmasterx Avatar asked Mar 20 '23 08:03

jmasterx


1 Answers

sscanf() is probably the most straightforward option. It is a C library function, so purists might disapprove it.

Here is an example:

int year;
int month;
int day;
int hour;
int min;
int sec;

const char * str = "2014-06-10 20:05:57";

if (sscanf(str, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &min, &sec) == 6)
{
    // sscanf() returns the number of elements scanned, so 6 means the string had all 6 elements.
    // Else it was probably malformed.
}

And here is a live test.

Another nice solution would also be to use a C++11 regex which would make for a more robust parsing of the string.

like image 156
glampert Avatar answered Mar 29 '23 02:03

glampert