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.
>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.