Here’s a demonstration of how to use strptime
and a list of format strings to validate, for example, a supplied ISO 8601 date in C or C++. You can play with the code below over at https://ideone.com/4Em3v1. It’s not an extensive list of all ISO 8601 dates, but these are the ones that work within a MySQL query. One improvement that could be made is to handle timezones in datetime strings like ’2010-01-01T01:01:01-7:00′ and potentially micro seconds (if possible).
This is also a good demonstration for how to easily loop through all elements in an array of undefined size in C.
#define _GNU_SOURCE #include <stdio.h> #include <time.h> #include <string.h> static int is_valid_iso8601_date_value(char *in) { struct tm result; char **f; char *ret; char *formats[] = { "%Y", "%Y-%m", "%y-%m", "%Y-%m-%d", "%y-%m-%d", "%Y%m%d", "%y%m%d", "%Y-%m-%d %T", "%y-%m-%d %T", "%Y%m%d%H%M%S", "%y%m%d%H%M%S", "%Y-%m-%dT%T", "%y-%m-%dT%T", "%Y-%m-%dT%TZ", "%y-%m-%dT%TZ", "%Y-%m-%d %TZ", "%y-%m-%d %TZ", "%Y%m%dT%TZ", "%y%m%dT%TZ", "%Y%m%d %TZ", "%y%m%d %TZ", NULL }; memset(&result, 0, sizeof(result)); for (f = formats; f && *f; f++) { ret = strptime(in, *f, &result); if (ret && *ret == '