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:
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
).Datetime String: Define a string representing a datetime value in the format "YYYY-MM-DDTHH:MM:SS".
Time Structure: Declare a struct (
timeStruct
) of typestruct tm
to store the broken-down components of the datetime.Datetime Parsing: Use the
strptime
function to parse the datetime string into astruct tm
object. The format string "%Y-%m-%dT%H:%M:%S" specifies the expected format of the datetime string.Error Checking - Parsing: Check if the
strptime
function successfully parsed the datetime string. If it returnsNULL
, print an error message to standard error and exit the program with a failure status.Datetime to Timestamp Conversion: Use the
mktime
function to convert thestruct tm
object into a timestamp (time_t
).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.Print Timestamp: If parsing and conversion are successful, print the timestamp to standard output.
Exit Status: Return
EXIT_SUCCESS
if the program executes successfully, andEXIT_FAILURE
if there is an error.