You can use the time
library and the strftime
function to print the current date in C. Here is an example of how you can do this:
Example:
#include <stdio.h>
#include <time.h>
void main(void)
{
// Get the current time
time_t current_time = time(NULL);
// Convert the time to a string using the desired format
char date_string[20];
strftime(date_string, 20, "%Y-%m-%d", localtime(¤t_time));
// Print the date string
printf("The current date is: %s\n", date_string);
}
Program Output:
The current date is: 2022-12-26
The following steps are taken in the above program to print the date in the required format:
- First, you will need to include the
time.h
header file, which provides functions for working with dates and times. - Next, you will need to get the current time. You can do this using the
time
function, which returns the current calendar time as a value of typetime_t
. This value is typically represented as the number of seconds since the epoch (midnight on January 1, 1970). - Now that you have the current time, the
localtime
function converts this value to astruct tm
, representing a calendar date and time broken down into its individual components (year, month, day, hour, minute, etc.). - The
strftime
function converts thestruct tm
value to a string using a specified format. In this example, the format string is "%Y-%m-%d", which specifies that the output should be in the form "YYYY-MM-DD", where YYYY is the year, MM is the month, and DD is the day. You can use a variety of format specifiers to customize the output to your liking. - Finally, the date string is printed using the
printf
function.