Date format dd-mm-yyyy in C
Tags: c
Published: 2023-05-29 10:11:36

<p>When working with <strong>dates in C</strong>, it's essential to understand the date system, date format, and how C handles dates. One common date format is <strong>dd-mm-yyyy</strong>, 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 <strong>date to dd-mm-yyyy format in C</strong>. Whether you prefer using built-in functions or custom solutions, I've got you covered. So let's dive in!</p>

<section>
<h2><span style="font-family:arial,helvetica,sans-serif;"><strong>Date in C</strong></span></h2>
<p>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.</p>

<h3><span style="font-family:arial,helvetica,sans-serif;"><strong>Date system</strong></span></h3>
<p>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.</p>

<h3><span style="font-family:arial,helvetica,sans-serif;"><strong>How C handles date?</strong></span></h3>
<p>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:</p>
<ul>
<li><strong>time()</strong>: returns the current time as the number of seconds since the Unix epoch.</li>
<li><strong>localtime()</strong>: 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.</li>
<li><strong>strftime()</strong>: formats a tm structure into a string representation of the date and time, using a specific format specifier.</li>
</ul>
<p>Remember these functions, we will come back to them later. </p>
</section>

<section>
<h2><span style="font-family:arial,helvetica,sans-serif;"><strong>How to convert date to format dd-mm-yyyy?</strong></span></h2>
<p>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.</p>

<h3><span style="font-family:arial,helvetica,sans-serif;"><strong>Solution 1: Using sprintf() </strong></span></h3>
<p>One way to convert a date to dd-mm-yyyy format is to use the <strong>sprintf()</strong> function, which allows you to format a string just like 'printf()'. Here's an example:</p>
<pre><code>#include <stdio.h>
#include <time.h>

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;
}</code></pre>

<p>You can see we are using time_t and struct tm type in our code:</p>
<ul>
<li><i>time_t</i> is a data type defined in the <time.h> header file in C. It represents time in seconds since the Unix epoch (January 1, 1970, 00:00:00 UTC)</li>
<li><i>struct tm</i> is a structure defined in the same <time.h> header, contains fields for the various components of calendar date and time, such as the year, month, day, hour, minute, and second.</li>
</ul>
<p>Now let's take a look at these two lines of code:</p>
<ul>
<li><i>now = time(NULL)</i> 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.</li>
<li><i>local = localtime(&now)</i> takes the 'time_t' value stored in now and converts it into a 'struct tm' value representing the local time.</li>
</ul>
<p>Then, we are formatting the date string in the <strong>date_str</strong> array, by accessing values of the date through <strong>local</strong> variable. The <strong>%02d</strong> specifier ensures that the day and month are zero-padded to two digits, and the <strong>%04d</strong> 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).</p>

<h3><span style="font-family:arial,helvetica,sans-serif;"><strong>Solution 2: Using strftime()</strong></span></h3>
<p>You can also use the <strong>strftime()</strong> function to achieve similar result. We use the same code as in solution 1 but replace one line only:</p>
<pre><code>//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);</code></pre>
<p>The "%d-%m-%Y" format specifier produces the same result as the "%02d-%02d-%04d" specifier used in the previous example.</p>


<h3><span style="font-family:arial,helvetica,sans-serif;"><strong>Solution 3: Extended custom function</strong></span></h3>
<p>Let's write a custom function that performs the conversion:</p>
<pre><code>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);
}</code></pre>
<p>The <strong>date_to_string()</strong> 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.</p>
<p>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:</p>
<pre><code>const char *months[] = {
   "", "Jan", "Feb", "Mar", "Apr", "May", "Jun",
   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
};</code></pre>
<p>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.</p>
<pre><code>/*Multiple type of separators
dd/mm/yyyy
dd.mm.yyyy
dd|mm|yyyy
*/</code></pre>
<p>Here's an example of extended version of the 'date_to_string' function:</p>
<pre><code>#include <stdio.h>
#include <string.h>

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;
}</code></pre>
<p>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.</p>
<p>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.</p>
</section>

<section>
<h2><span style="font-family:arial,helvetica,sans-serif;"><strong>Conclusion</strong></span></h2>
<p>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 <strong>converting dates to the dd-mm-yyyy format</strong>, 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.</p>