1
Mar

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 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 == '\0')
            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;
    }
    else
    {
    	printf("%s is not a valid iso8601 date!", date_str);
		return 1;
    }
}

Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:


There's 0 Comment So Far

Share your thoughts, leave a comment!