Date: 2018may14
Update: 2025oct20
Language: C/C++
Level: novice
Q. C/C++: How to display the 4-digit year?
(How to get the 4-digit year into a string)
A. Use strftime() or snprintf() as shown in a full example:
#include <time.h>
#include <stdio.h> // For snprintf()
int main() {
struct tm here;
const time_t now = time(NULL);
localtime_r(&now, &here);
// Using strftime()
{
char buf[100];
strftime(buf, sizeof(buf), "%Y", &here);
// You almost certainly don't want %G.
printf("year from strftime=%s\n", buf);
}
// Using snprintf()
{
char buf[100];
snprintf(buf, sizeof(buf), "%d", here.tm_year + 1900);
// Don't forget to add 1900
printf("year from snprintf=%s\n", buf);
}
}
Output (at one time):
year from strftime=2025
year from snprintf=2025