[英]How can I compare 2 dates converting from broken-down time to calendar time?
[英]How to convert UNIX time stamps (UTC) to broken-down time?
我已经分解了时间,然后我将其转换为 UTC 中的 UNIX 时间戳,并且没有使用 _mkgmtime 而不是 mktime(应用本地时区)的 DST。 这工作正常。 我现在想要的是在没有 DST/TimeZone 更改的情况下将生成的 UNIX 时间戳转换回完全相同的细分时间。 我尝试使用 strftime() 但它转换为本地时区。 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);
}
我总是用这张表这样的东西来思考这样的问题。 要从第一列中的内容转换为其他列中的内容,请调用指示的函数。
时间_t | 结构 tm (UTC) | 结构 tm(本地) | 细绳 | 自定义字符串 | |
---|---|---|---|---|---|
时间_t | - | 时间 | 当地时间 | 时间 | 不适用 |
结构 tm (UTC) | 时间* | - | 不适用 | 时间 | 时间 |
结构 tm(本地) | 时间 | 不适用 | - | 时间 | 时间 |
您想将time_t
转换为struct tm
UTC,因此您想要的函数是gmtime
。
我没有包含用于从字符串转换的行,因为这样做的函数不是标准的。 也许最著名的是strptime
,它将自定义字符串转换回struct tm
,使其或多或少是strftime
的倒数。
(公平地说, timegm
也不是完全标准的。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.