datetime - C code for date time format validation. specified format is "YYYYMMDDHHMMSSmmmmmm" -
i need validate date-time value "yyyymmddhhmmssmmmmmm
" format. hoping need find out tested working c code validate date time value above format. further, have date-time value 201304011031000000
. need function verify whether valid date or not.[isdatetime()
]
below each parts of formats.
yyyy : year mm : month dd : day hh : hour mm : minutes ss : seconds mmmmmm: micro-seconds
if you're on posix system, looks should handled strptime()
, 'milliseconds' (or microseconds) part not handled strptime()
or other standard conversion function know of.
assuming question asking microseconds, use variation on theme provided by:
#include <stdio.h> #include <string.h> #include <time.h> int main(void) { const char datetime[] = "20130417221633012345"; // yyyymmddhhmmssffffff struct tm time_val; unsigned microsecs; const char *end = strptime(datetime, "%y%m%d%h%m%s", &time_val); if (end != 0) { int nbytes; if (strlen(end) == 6 && sscanf(end, "%6u%n", µsecs, &nbytes) == 1 && nbytes == 6) { char buffer[32]; strftime(buffer, sizeof(buffer), "%y-%m-%d %h:%m:%s", &time_val); printf("%s = %s.%.6u\n", datetime, buffer, microsecs); } } return 0; }
revised requirement
#include <stdio.h> #include <string.h> #include <time.h> int isdatetime(const char *datetime) { // datetime format yyyymmddhhmmssffffff struct tm time_val; unsigned microsecs; int nbytes; const char *end = strptime(datetime, "%y%m%d%h%m%s", &time_val); if (end != 0 && strlen(end) == 6 && sscanf(end, "%6u%n", µsecs, &nbytes) == 1 && nbytes == 6) return 1; // valid return 0; // invalid }
Comments
Post a Comment