clocaltime

localtime() giving the wrong date in C


I'm trying to print out the local time on my computer using C' localtime() function;

The default format of my locale is mm/dd/yyyy, so The expected output is: 03/04/2023 12:51:43 But I get: 04/02/2023 12:51:43 I was thinking, maybe the localtime function does not follow the mm/dd/yyyy, and everything would be correct except the month (behind by 1)? It is really confusing to me. This is my code:

#include <time.h>
#include <stdio.h>
int main(void)
{
    time_t rawtime = time(NULL);
    struct tm *ptime = localtime(&rawtime);
    printf("The time is: %02d/%02d/%04d %02d:%02d:%02d\n",
           ptime->tm_mday, ptime->tm_mon, ptime->tm_year + 1900,
           ptime->tm_hour, ptime->tm_min, ptime->tm_sec);
    return 0;
}

I have seen many quetions with localtime() giving the wrong time, which is due to the time zone, but I have no idea what this one my be due to; Can anyone help spot what I am doing wrong? Thanks!


Solution

  • The tm_mon field specifies the number of months since January, so for the month of March this field will have the value 2.

    Also, your output has the day followed by the month because that's the order in which you're printing them.

    To print the month correctly, and to print the month first, you want:

    printf("The time is: %02d/%02d/%04d %02d:%02d:%02d\n",
           ptime->tm_mon + 1, ptime->tm_mday, ptime->tm_year + 1900,
           ptime->tm_hour, ptime->tm_min, ptime->tm_sec);