clocaltime

Can't get right time in C with localtime()?


I have used the following code to get time and date in India, but the time i get is not the right time.

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

int main() {
  struct timespec ts;
  struct tm *ti;
  char time_buf[80];

  // Get the current time
  clock_gettime(CLOCK_REALTIME, &ts);

  // Convert the time to the local time zone in India
  ti = localtime(&ts.tv_sec);

  // Format the time as a string, including the time zone offset
  strftime(time_buf, sizeof(time_buf), "%Y-%m-%dT%H:%M:%S%z", ti);

  // Print the time string
  printf("Local time in India: %s\n", time_buf);

  return 0;
}

What is wrong with this code and how can i get the right time. And even with gmtime() function i get the same date and time. I used this online c compiler- [https://www.onlinegdb.com/online_c_compiler]-

https://www.onlinegdb.com/online_c_compiler

This is the output

while the actual time is 4:30 PM


Solution

  • The C date and time functions all assume a "local time zone", but it's basically a global variable, set outside of your program.

    On Unix and Unix-like systems, the local time zone is set by the file /etc/localtime, and can be overridden on a per-process basis by the environment variable TZ. That scheme works fine when the system you're using is located where you are, or where your login environment is under your control. But you say you're using an online C compiler, meaning that you're stuck with whatever time zone it's set to.

    However! On Unix and Unix-like systems, a process can reset its own environment variables using the putenv and setenv functions. So if you make the following simple change to your program, it should work better:

    #include <stdlib.h>
    
    ...
    
    char *zone = "Asia/Kolkata";
    
    /* Set the time zone */
    setenv("TZ", zone, 1);
    tzset();
    
    ... the rest of your code ...
    
    printf("Local time in %s: %s\n", zone, time_buf);
    

    Note also the call to tzset, which may be necessary to make sure that the C library catches up with the fact that you've just adjusted the TZ variable.

    If you do have control over the environment where your program is running, things are a little easier, and you don't usually have to muck around with calls to setenv and tzset. On a Unix or Unix-like system, you just have to set the TZ environment variable using ordinary shell techniques. You can either invoke something like

    export TZ=Asia/Kolkata
    

    at the shall prompt before you run your program, or put that line in your .profile or .bash_profile file so it's run every time you log in.

    [Disclaimer: I can't promise that the setenv technique will work under your on-line C compiler, as it assumes that the on-line C compiler is running on a Unix or Unix-like system, with control over its own environment. But it's likely to work.]