How to convert multiple date formats to YYYY-MM-DD in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

/*
    Convert multiple date formats to YYYY-MM-DD.

    Supported formats:
      1. DD/MM/YYYY
      2. MM-DD-YYYY
      3. YYYY.MM.DD
      4. Month DD, YYYY   (e.g., January 5, 2024)
      5. YYYY/MM/DD
      6. YYYY-MM-DD       (already normalized)

    Architecture notes:
      - Each format has its own parser function.
      - A dispatcher tries each parser until one succeeds.
      - This avoids fragile monolithic parsing logic.
      - Complexity: O(n) over number of formats; trivial cost.
      - Memory: small stack buffers; no dynamic allocations except minimal ones.
      - Security: careful bounds checking; no unsafe pointer arithmetic.
      - Error handling: invalid formats return 0 (false).
      - Tests: main() includes multiple test cases, including edge cases.

    Pitfalls:
      - Month names must be mapped carefully.
      - Whitespace around month names must be handled.
      - Leading zeros must be preserved in output.

    Performance notes:
      - String scanning is cheap; no regex engine overhead.
      - For extremely high-throughput scenarios, consider pre-tokenizing input.
*/

// ------------------ Month name mapping ------------------
int monthNameToNumber(const char *name) {
    static const char *months[] = {
        "January","February","March","April","May","June",
        "July","August","September","October","November","December"
    };

    for (int i = 0; i < 12; i++) {
        if (strcmp(name, months[i]) == 0) return i + 1;
    }
    
    return 0; // invalid
}

// ------------------ Utility: format YYYY-MM-DD ------------------
void formatYMD(char *out, int y, int m, int d) {
    sprintf(out, "%04d-%02d-%02d", y, m, d);
}

// ------------------ Parsers ------------------

// 1. DD/MM/YYYY
int parseDDMMYYYY(const char *s, char *out) {
    int d, m, y;
    
    if (sscanf(s, "%d/%d/%d", &d, &m, &y) == 3) {
        if (y > 0 && m >= 1 && m <= 12 && d >= 1 && d <= 31) {
            formatYMD(out, y, m, d);
            return 1;
        }
    }
    
    return 0;
}

// 2. MM-DD-YYYY
int parseMMDDYYYY(const char *s, char *out) {
    int d, m, y;
    
    if (sscanf(s, "%d-%d-%d", &m, &d, &y) == 3) {
        if (y > 0 && m >= 1 && m <= 12 && d >= 1 && d <= 31) {
            formatYMD(out, y, m, d);
            return 1;
        }
    }
    
    return 0;
}

// 3. YYYY.MM.DD
int parseYYYYMMDDDots(const char *s, char *out) {
    int d, m, y;
    
    if (sscanf(s, "%d.%d.%d", &y, &m, &d) == 3) {
        if (y > 0 && m >= 1 && m <= 12 && d >= 1 && d <= 31) {
            formatYMD(out, y, m, d);
            return 1;
        }
    }
    
    return 0;
}

// 4. Month DD, YYYY
int parseMonthDDYYYY(const char *s, char *out) {
    char month[20];
    int d, y;

    // Extract month name, day, year
    if (sscanf(s, "%19s %d, %d", month, &d, &y) == 3) {
        int m = monthNameToNumber(month);
        if (m > 0 && d >= 1 && d <= 31 && y > 0) {
            formatYMD(out, y, m, d);
            return 1;
        }
    }
    
    return 0;
}

// 5. YYYY/MM/DD
int parseYYYYMMDDSlashes(const char *s, char *out) {
    int d, m, y;
    
    if (sscanf(s, "%d/%d/%d", &y, &m, &d) == 3) {
        if (y > 0 && m >= 1 && m <= 12 && d >= 1 && d <= 31) {
            formatYMD(out, y, m, d);
            return 1;
        }
    }
    
    return 0;
}

// 6. YYYY-MM-DD (already normalized)
int parseNormalized(const char *s, char *out) {
    int d, m, y;
    
    if (sscanf(s, "%d-%d-%d", &y, &m, &d) == 3) {
        if (y > 0 && m >= 1 && m <= 12 && d >= 1 && d <= 31) {
            formatYMD(out, y, m, d);
            return 1;
        }
    }
    
    return 0;
}

// ------------------ Dispatcher ------------------
int convertToCanonical(const char *s, char *out) {
    // Order chosen for common formats first
    if (parseNormalized(s, out)) return 1;
    if (parseDDMMYYYY(s, out)) return 1;
    if (parseMMDDYYYY(s, out)) return 1;
    if (parseYYYYMMDDDots(s, out)) return 1;
    if (parseMonthDDYYYY(s, out)) return 1;
    if (parseYYYYMMDDSlashes(s, out)) return 1;
    
    return 0;
}

// ------------------ Tests ------------------
int main(void) {
    const char *tests[] = {
        "05/01/2024",
        "12-31-2023",
        "2024.02.09",
        "January 5, 2024",
        "2024/09/17",
        "2024-09-17",
        "BadFormat",
        "Feb 30, 2024",   // invalid month name
        "April 31, 2024", // invalid day
        "7/7/2024"        // single-digit day/month
    };

    char out[20];

    for (size_t i = 0; i < sizeof(tests)/sizeof(tests[0]); i++) {
        if (convertToCanonical(tests[i], out)) {
            printf("Input: %-20s -> %s\n", tests[i], out);
        } else {
            printf("Input: %-20s -> Invalid or unsupported format\n", tests[i]);
        }
    }

    return 0;
}


/*
run:

Input: 05/01/2024           -> 2024-01-05
Input: 12-31-2023           -> 2023-12-31
Input: 2024.02.09           -> 2024-02-09
Input: January 5, 2024      -> 2024-01-05
Input: 2024/09/17           -> 2024-09-17
Input: 2024-09-17           -> 2024-09-17
Input: BadFormat            -> Invalid or unsupported format
Input: Feb 30, 2024         -> Invalid or unsupported format
Input: April 31, 2024       -> 2024-04-31
Input: 7/7/2024             -> 2024-07-07

*/

 



answered Sep 24 by avibootz
...