Home > Net >  How can I make strftime show year as in 2022 instead of 22? Is there a way?
How can I make strftime show year as in 2022 instead of 22? Is there a way?

Time:09-15

time_t rawtime;
time(&rawtime);
struct tm* timeinfo = localtime(&rawtime);
strftime(arr, sizeof(arr)-1 , "%d/%m/%y", timeinfo);
puts(arr);

The output is 15/9/22, I want it 15/9/2022.I need it to be stored in a char array

CodePudding user response:

Just use %Y instead of lowercase y. Clear in documentation.

strftime(arr, sizeof(arr)-1 , "%d/%m/%Y", timeinfo);

CodePudding user response:

Based on additional information supplied by the OP under @Hogan's answer, here is the fix:

Change:

strftime(arr, sizeof(arr)-1 , "%d/%m/%y", timeinfo);

to

strftime( arr, sizeof arr, "%d/%m/%Y", timeinfo );

The 'Y' will give a 4 digit year and the OP has stated that the destination array is "minimal" for "dd/mm/yyyy" (11 bytes only) with nothing to spare. By subtracting 1 in the parameter list, strftime() did the best that it could.

Like fgets( ) and unlike the dangerous strncat( ), one uses this function (passing the full buffer size) safe in the knowledge that the function "knows" it is returning a "null terminated string".

EDIT: Credit where credit is due. @Hogan asked the "pivotal" question that led to this answer.

  •  Tags:  
  • c
  • Related