简体   繁体   English

如何将 UNIX 时间戳 (UTC) 转换为故障时间?

[英]How to convert UNIX time stamps (UTC) to broken-down time?

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).我已经分解了时间,然后我将其转换为 UTC 中的 UNIX 时间戳,并且没有使用 _mkgmtime 而不是 mktime(应用本地时区)的 DST。 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.我现在想要的是在没有 DST/TimeZone 更改的情况下将生成的 UNIX 时间戳转换回完全相同的细分时间。 I tried using strftime() but it converts to local timezone.我尝试使用 strftime() 但它转换为本地时区。 The same goes with localtime(). 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);
}

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时间_t struct tm (UTC)结构 tm (UTC) struct tm (local)结构 tm(本地) string细绳 custom string自定义字符串
time_t时间_t - - gmtime时间 localtime当地时间 ctime时间 n/a不适用
struct tm (UTC)结构 tm (UTC) timegm *时间* - - n/a不适用 asctime时间 strftime时间
struct tm (local)结构 tm(本地) 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 .您想将time_t转换为struct tm UTC,因此您想要的函数是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 .也许最著名的是strptime ,它将自定义字符串转换回struct tm ,使其或多或少是strftime的倒数。

(In fairness, timegm isn't perfectly standard, either.) (公平地说, timegm也不是完全标准的。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM