Write a to display present date and time using c language.
#include <stdio.h>
#include <time.h>
int main() {
// Get the current time
time_t now = time(NULL);
// Check if time() returns an error
if (now == -1) {
printf("Failed to get the current time.\n");
return 1;
}
// Convert time to local time structure
struct tm *local = localtime(&now);
// Check if localtime() returns NULL
if (local == NULL) {
printf("Failed to convert to local time.\n");
return 1;
}
// Print the current date and time in the format: YYYY-MM-DD HH:MM:SS
printf("Current date and time: %04d-%02d-%02d %02d:%02d:%02d\n",
local->tm_year + 1900, // Year since 1900
local->tm_mon + 1, // Month (0-11)
local->tm_mday, // Day of the month
local->tm_hour, // Hours since midnight (0-23)
local->tm_min, // Minutes after the hour (0-59)
local->tm_sec); // Seconds after the minute (0-59)
return 0;
}
Comments
Post a Comment