Handling exceptions during datetime conversion

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

int main() {
    const char *datetimeString = "2023-12-04T14:30:00";
    struct tm timeStruct;

    if (strptime(datetimeString, "%Y-%m-%dT%H:%M:%S", &timeStruct) == NULL) {
        fprintf(stderr, "Error parsing datetime string\n");
        return EXIT_FAILURE;
    }

    time_t timestamp = mktime(&timeStruct);

    if (timestamp == -1) {
        fprintf(stderr, "Error converting datetime to timestamp\n");
        return EXIT_FAILURE;
    }

    printf("Timestamp: %ld\n", timestamp);

    return EXIT_SUCCESS;
}

Explanation:

  1. Header Files: Include necessary header files for standard input/output operations (stdio.h), dynamic memory allocation (stdlib.h), and date and time manipulation (time.h).

  2. Datetime String: Define a string representing a datetime value in the format "YYYY-MM-DDTHH:MM:SS".

  3. Time Structure: Declare a struct (timeStruct) of type struct tm to store the broken-down components of the datetime.

  4. Datetime Parsing: Use the strptime function to parse the datetime string into a struct tm object. The format string "%Y-%m-%dT%H:%M:%S" specifies the expected format of the datetime string.

  5. Error Checking - Parsing: Check if the strptime function successfully parsed the datetime string. If it returns NULL, print an error message to standard error and exit the program with a failure status.

  6. Datetime to Timestamp Conversion: Use the mktime function to convert the struct tm object into a timestamp (time_t).

  7. Error Checking - Conversion: Check if the mktime function successfully converted the datetime to a timestamp. If the result is -1, print an error message to standard error and exit the program with a failure status.

  8. Print Timestamp: If parsing and conversion are successful, print the timestamp to standard output.

  9. Exit Status: Return EXIT_SUCCESS if the program executes successfully, and EXIT_FAILURE if there is an error.