简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM