parsing - how do I parse an iso 8601 date (with optional milliseconds) to a struct tm in C++? -
i have string should specify date , time in iso 8601 format, may or may not have milliseconds in it, , wanting struct tm
millisecond value may have been specified (which can assumed 0 if not present in string).
what involved in detecting whether string in correct format, converting user-specified string struct tm
, millisecond values?
if weren't millisconds issue, use c function strptime()
, not know defined behavior of function supposed when seconds contain decimal point.
as 1 final caveat, if @ possible, prefer solution not have dependency on functions found in boost (but i'm happy accept c++11 prerequisite).
the input going like:
2014-11-12t19:12:14.505z
or
2014-11-12t12:12:14.505-5:00
z
, in case, indicates utc, time zone might used, , expressed + or - hours/minutes offset gmt. decimal portion of seconds field optional, fact may there @ why cannot use strptime()
or std::get_time()
, not describe particular defined behavior if such character found in seconds portion of string.
you can use c
's sscanf
(http://www.cplusplus.com/reference/cstdio/sscanf/) parse it:
const char *datestr = "2014-11-12t19:12:14.505z"; int y,m,d,h,m; float s; sscanf(datestr, "%d-%d-%dt%d:%d:%fz", &y, &m, &d, &h, &m, &s);
if have std::string
can called (http://www.cplusplus.com/reference/string/string/c_str/):
std::string datestr = "2014-11-12t19:12:14.505z"; sscanf(datestr.c_str(), "%d-%d-%dt%d:%d:%fz", &y, &m, &d, &h, &m, &s);
if should handle different timezones need use sscanf
return value - number of parsed arguments:
int tzh = 0, tzm = 0; if (6 < sscanf(datestr.c_str(), "%d-%d-%dt%d:%d:%f%d:%dz", &y, &m, &d, &h, &m, &s, &tzh, &tzm)) { if (tzh < 0) { tzm = -tzm; // fix sign on minutes. } }
and can fill tm
(http://www.cplusplus.com/reference/ctime/tm/) struct:
tm time; time.tm_year = y - 1900; // year since 1900 time.tm_mon = m - 1; // 0-11 time.tm_mday = d; // 1-31 time.tm_hour = h; // 0-23 time.tm_min = m; // 0-59 time.tm_sec = (int)s; // 0-61 (0-60 in c++11)
it can done std::get_time
(http://en.cppreference.com/w/cpp/io/manip/get_time) since c++11
@barry mentioned in comment how parse iso 8601 date (with optional milliseconds) struct tm in c++?
Comments
Post a Comment