Skip to main content

C Function to Validate ISO 8601 Date Formats Using ‘strptime’

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 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-%m-%d %T",
        "%y-%m-%d %T",
        "%Y-%m-%d %TZ",
        "%y-%m-%d %TZ",
        "%Y%m%d %TZ",
        "%y%m%d %TZ",

    memset(&result, 0, sizeof(result));

    for (f = formats; f && *f; f++)
        ret = strptime(in, *f, &result);
        if (ret && *ret == '')
            return 1;

    return 0;

int main(void) {
	char date_str[] = "2010-01-01T01:01:01Z";
    if (is_valid_iso8601_date_value(date_str))
    	printf("%s is a valid iso8601 date!", date_str);
        return 0;
    	printf("%s is not a valid iso8601 date!", date_str);
		return 1;