Home > Blockchain >  How to convert UNIX time stamps (UTC) to broken-down time?
How to convert UNIX time stamps (UTC) to broken-down time?

Time:05-20

I have broken-down time which I then convert to UNIX timestamp in UTC and without DST with _mkgmtime instead of mktime(which applies the local timezone). This works fine. What I now want is to convert the UNIX timestamp generated back to broken-down time exactly the same with no DST/TimeZone changes. I tried using strftime() but it converts to local timezone. The same goes with localtime().

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

int main() {
    struct tm info;
    char buffer[80];
    
    info.tm_year = 2022 - 1900;
    info.tm_mon = 5 - 1;
    info.tm_mday = 19;
    info.tm_hour = 15;
    info.tm_min = 3;
    info.tm_sec = 0;
    info.tm_isdst = 0;
    
    uint32_t time_passed_utc = _mkgmtime(&info);
    printf("time_passed_utc uint32: %lu\n", time_passed_utc); // this returns correctly "1652972580"
    strftime(buffer, sizeof(buffer), "time_passed_utc-> %c", &info );
    printf(buffer); // this returns correctly "05/19/22 15:03:00"
    
    printf("\n\n");
    
    time_t rawtime = 1652972580;
    
    struct tm  ts;
    char       buf[80];
    
    // Format time, "ddd yyyy-mm-dd hh:mm:ss zzz"
    ts = *localtime(&rawtime);
    ts.tm_isdst = 0; // no DST setting
    strftime(buf, sizeof(buf), "%a %Y-%m-%d %H:%M:%S %Z", &ts);
    printf("%s\n", buf);  // returns incorrectly "Thu 2022-05-19 18:03:00 E. Europe Standard Time" -> should have been "2022-05-19 15:03:00"
    
    return(0);
}

CodePudding user response:

I always think about questions like these using something like this table. To convert from something in the first column, to something in one of the other columns, call the indicated function.

time_t struct tm (UTC) struct tm (local) string custom string
time_t - gmtime localtime ctime n/a
struct tm (UTC) timegm * - n/a asctime strftime
struct tm (local) mktime n/a - asctime strftime

You want to convert a time_t to a struct tm in UTC, so the function you want is gmtime.

I didn't include rows for converting from strings, because the functions to do so aren't as standard. Perhaps the best-known is strptime, which converts from a custom string back to a struct tm, making it more or less the inverse of strftime.

(In fairness, timegm isn't perfectly standard, either.)

  •  Tags:  
  • c
  • Related