Time Formatting Parsing in C

#include <stdio.h>
#include <time.h>
#include <string.h>

void print_formatted_time(const char* format, const struct tm* timeinfo) {
    char buffer[80];
    strftime(buffer, sizeof(buffer), format, timeinfo);
    printf("%s\n", buffer);
}

int main() {
    time_t now;
    struct tm *timeinfo;
    char buffer[80];

    // Get current time
    time(&now);
    timeinfo = localtime(&now);

    // Format time according to RFC3339
    strftime(buffer, sizeof(buffer), "%Y-%m-%dT%H:%M:%S%z", timeinfo);
    printf("%s\n", buffer);

    // Parse a time string
    struct tm parsed_time = {0};
    strptime("2012-11-01T22:08:41+00:00", "%Y-%m-%dT%H:%M:%S%z", &parsed_time);
    printf("%s", asctime(&parsed_time));

    // Custom time formatting
    print_formatted_time("%I:%M%p", timeinfo);
    print_formatted_time("%a %b %d %H:%M:%S %Y", timeinfo);
    print_formatted_time("%Y-%m-%dT%H:%M:%S.000000%z", timeinfo);

    // Parse a custom time format
    memset(&parsed_time, 0, sizeof(struct tm));
    strptime("8 41 PM", "%I %M %p", &parsed_time);
    printf("%s", asctime(&parsed_time));

    // Numeric representation using printf
    printf("%d-%02d-%02dT%02d:%02d:%02d-00:00\n",
           timeinfo->tm_year + 1900, timeinfo->tm_mon + 1, timeinfo->tm_mday,
           timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);

    // Demonstrate error handling (C doesn't have built-in error handling for time parsing)
    if (strptime("8:41PM", "%I:%M%p", &parsed_time) == NULL) {
        printf("Error parsing time\n");
    }

    return 0;
}

This C program demonstrates time formatting and parsing, which is conceptually similar to the original example. Here’s an explanation of the key points:

  1. We use the time.h library for time-related functions and string.h for string manipulation.

  2. The strftime function is used for formatting time, similar to the Format method in the original example.

  3. For parsing time strings, we use strptime, which is the C equivalent of the Parse function.

  4. Custom time formats are demonstrated using various format strings with strftime.

  5. For purely numeric representations, we use printf with individual components of the struct tm.

  6. Error handling in C for time parsing is typically done by checking the return value of strptime. If it returns NULL, an error occurred during parsing.

Note that C doesn’t have as robust built-in support for time zones and some advanced time formatting features as the original language. The example here provides a simplified version that covers the main concepts.

To compile and run this program:

$ gcc time_formatting_parsing.c -o time_formatting_parsing
$ ./time_formatting_parsing

The output will be similar to the original example, showing various formatted times and parsed time strings.