DEV Community

AnkurRanpariya2005
AnkurRanpariya2005

Posted on • Edited on • Originally published at frontendscript.com

Date format dd-mm-yyyy in C

#c

When working with dates in C, it's essential to understand the date system, date format, and how C handles dates. One common date format is dd-mm-yyyy, which represents the day, month, and year separated by hyphens. Converting a date to this format can be necessary for data processing or display purposes. In this article, we'll explore different ways to convert a date to dd-mm-yyyy format in C. Whether you prefer using built-in functions or custom solutions, I've got you covered. So let's dive in!

Date in C

Dates are an essential aspect of programming, and handling them correctly is crucial for any program that relies on time-based functionality. In C, dates are typically stored as integers, with each digit representing a specific aspect of the date, such as day, month, and year.

Date system

The date system used in C is based on the Unix timestamp, which is the number of seconds that have elapsed since January 1, 1970, at 00:00:00 UTC. This system is also known as POSIX time or Unix epoch time. It is a widely used standard for representing dates and times in programming languages, operating systems, and other software applications.

How C handles date?

In C, the date and time functions are provided by the standard library "time.h." This library contains a set of functions that allow you to manipulate dates and times in various formats. Some of the most commonly used functions include:

  • time(): returns the current time as the number of seconds since the Unix epoch.
  • localtime(): converts a time_t value to a tm structure, which contains information about the local time, such as year, month, day, hour, minute, and second.
  • strftime(): formats a tm structure into a string representation of the date and time, using a specific format specifier.

Remember these functions, we will come back to them later.

How to convert date to format dd-mm-yyyy?

The default date format used in C is not dd-mm-yyyy, but rather yyyy-mm-dd. This format is also known as ISO 8601 and is widely used in international contexts. However, you will often need to convert dates to other formats, such as dd-mm-yyyy, to meet specific requirements. Fortunately, there are several ways to accomplish this task.

Solution 1: Using sprintf()

One way to convert a date to dd-mm-yyyy format is to use the sprintf() function, which allows you to format a string just like 'printf()'. Here's an example:

#include 
#include 

int main() {
   time_t now;
   struct tm *local;
   char date_str[11];

   now = time(NULL);
   local = localtime(&now);

   sprintf(date_str, "%02d-%02d-%04d", local->tm_mday, local->tm_mon + 1, local->tm_year + 1900);

   printf("Date: %s\n", date_str);

   return 0;
}

You can see we are using time_t and struct tm type in our code:

  • time_t is a data type defined in the header file in C. It represents time in seconds since the Unix epoch (January 1, 1970, 00:00:00 UTC)
  • struct tm is a structure defined in the same header, contains fields for the various components of calendar date and time, such as the year, month, day, hour, minute, and second.

Now let's take a look at these two lines of code:

  • now = time(NULL) gets the current time in seconds since the Unix epoch and stores it in the now variable of type 'time_t'. The NULL argument tells the 'time()' function to use the current time.
  • local = localtime(&now) takes the 'time_t' value stored in now and converts it into a 'struct tm' value representing the local time.

Then, we are formatting the date string in the date_str array, by accessing values of the date through local variable. The %02d specifier ensures that the day and month are zero-padded to two digits, and the %04d specifier ensures that the year is zero-padded to four digits. We add 1 to the month value (since January is 0) and 1900 to the year value (since the 'tm_year field' is the number of years since 1900).

Solution 2: Using strftime()

You can also use the strftime() function to achieve similar result. We use the same code as in solution 1 but replace one line only:

//sprintf(date_str, "%02d-%02d-%04d", local->tm_mday, local->tm_mon + 1, local->tm_year + 1900);
strftime(date_str, sizeof(date_str), "%d-%m-%Y", local);

The "%d-%m-%Y" format specifier produces the same result as the "%02d-%02d-%04d" specifier used in the previous example.

Solution 3: Extended custom function

Let's write a custom function that performs the conversion:

void date_to_string(char *str, const struct tm *timeptr) {
   sprintf(str, "%02d-%02d-%04d", timeptr->tm_mday, timeptr->tm_mon + 1, timeptr->tm_year + 1900);
}

The date_to_string() function takes a pointer to a 'tm' structure and a pointer to a character array. You can call and pass it the local time pointer and the date string array. But the content inside the function is the same as solution 1, using sprintf() to format the date as a string in dd-mm-yyy format.

We can improve our custom function by using a lookup table for month abbreviations. This can be useful if you need to perform the conversion frequently or want to avoid the overhead of formatting the date using sprintf() or other functions:

const char *months[] = {
   "", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};

Or if you don't like to use the hyphen symbol '-' between day, month, and year. No problem, you can adjust the code to allow for different date separators.

/*Multiple type of separators
dd/mm/yyyy
dd.mm.yyyy
dd|mm|yyyy
*/

Here's an example of extended version of the 'date_to_string' function:

#include 
#include 

void date_to_string(int day, int month, int year, char *str, const char *separator) {
   const char *month_abbr[] = {"", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
      "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
   char month_str[4];
   sprintf(month_str, "%s", month_abbr[month]);

   char day_str[3];
   sprintf(day_str, "%02d", day);

   char year_str[5];
   sprintf(year_str, "%04d", year);

   strcpy(str, day_str);
   strcat(str, separator);
   strcat(str, month_str);
   strcat(str, separator);
   strcat(str, year_str);
}

int main() {
   int day, month, year;
   char date_str[11];

   // Prompt the user for the date
   printf("Enter the date (dd-mm-yyyy): ");
   scanf("%d-%d-%d", &day, &month, &year);

   // Format the date using a custom function
   date_to_string(day, month, year, date_str, "-");

   printf("Date: %s\n", date_str);

   return 0;
}

In this example, we've extended the date_to_string() function to include a custom separator as an argument. We've also used a custom implementation for the month abbreviation, which we store in an array of string literals. We then use sprintf() to format the day, month, and year as strings and concatenate them with the separator character.

This extended date_to_string() function allows for greater customization of the output format, making it a versatile and flexible solution for date formatting in C.

Conclusion

This article has covered various aspects of working with dates in C, including the date system, date format, and how C handles dates. Additionally, we have explored multiple solutions for converting dates to the dd-mm-yyyy format, which can be useful for displaying dates in a user-friendly manner or performing date arithmetic. By understanding the techniques presented in this article, you as a C programmer can effectively work with dates in your programs.

Top comments (1)

Collapse
 
pauljlucas profile image
Paul J. Lucas

Your declaration for month_abbr should include static. However, there's absolutely no reason to copy it to month_str or for month_str to exist. Just use month_abbr directly.

You should simply use a single sprintf(). You don't need any of the temporary string buffers and so don't have to copy the strings out of them:

sprintf( str, "%02d%s%s%s%04d", day, separator, month_abbr[month], separator, year );
Enter fullscreen mode Exit fullscreen mode