C Programming Examples Tutorial Index
C Function Programs

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:


#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(&current_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:

  1. First, you will need to include the time.h header file, which provides functions for working with dates and times.
  2. 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 type time_t. This value is typically represented as the number of seconds since the epoch (midnight on January 1, 1970).
  3. Now that you have the current time, the localtime function converts this value to a struct tm, representing a calendar date and time broken down into its individual components (year, month, day, hour, minute, etc.).
  4. The strftime function converts the struct 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.
  5. Finally, the date string is printed using the printf function.