Print time stamp in c

49 views Asked by At

I used the following code in c for time stamping. Singapore time zone should be UTC+08. But it came out as 0000

time_t now;
time(&now);
char ts[sizeof "1970-01-01T00:00:00+00:00"];
strftime(ts, sizeof ts, "%FT%T%z", gmtime(&now)); 

The output is "2024-03-28T03:20:13+0000" Time is also wrong. Should be 11:20 but it shows as 03:20. How can I make changes?

1

There are 1 answers

3
asmgx On BEST ANSWER

It seems like you are using the gmtime() function, which converts the time to Coordinated Universal Time (UTC) time zone, hence the "+0000" in your output. To get the time in the Singapore time zone (UTC+08:00), you should use the localtime() function instead of gmtime(). However, since localtime() adjusts for the local time zone of the system, you need to manually adjust it to Singapore time zone.

Here's how you can modify your code to get the time in the Singapore time zone:

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

int main() {
    time_t now;
    time(&now);
    
    // Get the time structure in local time zone
    struct tm *local_time = localtime(&now);
    
    // Adjust for Singapore time zone (+08:00)
    local_time->tm_hour += 8;
    
    // Correct hour if it exceeds 24
    if (local_time->tm_hour >= 24) {
        local_time->tm_hour -= 24;
    }
    
    char ts[sizeof "1970-01-01T00:00:00+08:00"];
    strftime(ts, sizeof ts, "%FT%T%z", local_time);
    
    printf("%s\n", ts);
    
    return 0;
}

This code adjusts the hour of the time structure obtained from localtime() to match the Singapore time zone. Then, it formats the timestamp using strftime() with the "%z" format specifier to include the time zone information.

Please note that this solution assumes that the time zone offset for Singapore is always UTC+08:00, which might not be accurate during daylight saving time changes. If you need to handle daylight saving time changes, you may need to use a more sophisticated approach or a library that provides timezone handling functionality.