Why does year return 116 instead of 2016 in C?

599 views Asked by At

I have this code:

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

int main(void) {

    time_t rawtime = time(NULL);
    struct tm *ptm = localtime(&rawtime);
    printf("The time is: %02d:%02d:%02d\n", ptm->tm_hour, 
           ptm->tm_min, ptm->tm_sec);
    printf("The date is: %02d:%02d:%04d\n.", ptm->tm_mday, ptm->tm_mon, ptm->tm_year);
    return 0;
}

When I run it, it returns the value of tm_year as 116 instead of 2016. Can anyone tell me why?

2

There are 2 answers

4
ra4king On

The tm_year field is represented as years since 1900: https://linux.die.net/man/3/localtime

0
BrechtDeMan On

As tm_year is the number of years since 1900, you need to add 1900 to this.

Source: http://pubs.opengroup.org/onlinepubs/7908799/xsh/time.h.html

So you get:

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

int main(void) {

    time_t rawtime = time(NULL);
    struct tm *ptm = localtime(&rawtime);
    printf("The time is: %02d:%02d:%02d\n", ptm->tm_hour, 
           ptm->tm_min, ptm->tm_sec);
    printf("The date is: %02d:%02d:%04d\n.", ptm->tm_mday, ptm->tm_mon, ptm->tm_year+1900);
    return 0;
}