Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i display date in dd–mm-yyyy format with a leading zero when day or month is lesser than 10?

I am trying to save current date on a variable with the following format: 0301 (day and month).
I am using time function and the only problem I come across is that i cant seem to find a way to print the date with leading zero, for example I can only print 31 instead of 0301.
Any ways to fix it?

I used itoa() function to turn the integer of the day and month into 2 separate strings and then tried to edit the string characters separately but i couldn’t manage to do so.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

To display the date in the dd--mm-yyyy format with a leading zero when the day or month is less than 10, you can use the strftime function from the time.h header file.

#include <stdio.h>
#include <time.h>

int main() {
  time_t t = time(NULL);
  struct tm tm = *localtime(&t);

  char date[16];
  strftime(date, sizeof(date), "%d--%m-%Y", &tm);
  printf("Date: %s\n", date);

  return 0;
}

This code will get the current date and time and store it in the tm struct. The strftime function is then used to format the date and time in the dd--mm-yyyy format and store it in the date char array. The printf function is used to print the formatted date to the console.

The strftime function takes three arguments: the char array where the formatted date and time should be stored, the size of the char array, and a format string specifying the desired format. The %d and %m format specifiers are used to format the day and month with a leading zero when needed.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading