簡體   English   中英

為什么我使用 tm 時間得到不正確的時間?

[英]Why am I getting incorrect time using tm time?

我提前一分鍾減去當前時間,但是 C++ 說差異是 18000 秒,相當於 300 分鍾(4 小時)。 真的很困惑為什么會這樣。 這是我的代碼:

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

int main(){
    time_t timer; 
    struct tm t = {0}; 
    double seconds; 
    
    t.tm_year = 122; //2022
    t.tm_mon = 7 //august
    t.tm_mday = 29; //29
    t.tm_hour = 21; //10pm
    t.tm_min = 35; //35
    t.tm_sec = 0; 

    time(&timer); //get current time
    seconds = difftime(timer, mktime(&t)); 

    std::cout << seconds; 
}

C 庫中的time function 處理 UTC 時間,而mktime假定您的本地時間。 這在文檔中是明確的。

time() 以自 Epoch 1970-01-01 00:00:00 +0000 ( UTC ) 以來的秒數返回時間。

mktime() function 將分解的時間結構(表示為 local time )轉換為日歷時間表示。

考慮這段代碼:

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

int main(){
    struct tm t; 
    memset(&t,0,sizeof(tm));
    t.tm_year = 2022 - 1900;
    t.tm_mon = 8 - 1;  
    t.tm_mday = 29; 
    t.tm_hour = 23;
    t.tm_min = 28; 
    t.tm_sec = 0;
    t.tm_isdst = 1;
    
    time_t mktm = mktime(&t);
    time_t timer = time(0);

    double seconds = difftime(timer,mktm); 
    std::cout << seconds << std::endl;
    std::cout << mktm << std::endl;
    std::cout << timer << std::endl;

    struct tm local;
    localtime_r( &mktm, &local );
    std::cout << "gmtoff:" << local.tm_gmtoff << std::endl;
}

觀察我通過了t.tm_isdst=1因為我在芝加哥,目前正處於白天,我得到了這個:

$ g++ /tmp/test2.cpp -o ./test2
$ ./test2
30
1661833680
1661833710
gmtoff:-18000

因此,這告訴我時間結構僅比當前時間早 30 秒,這是您的預期結果。 我還要求打印負 18,000 秒(-5 小時)的本地時間 gmt 偏移量,這似乎是正確的。

請注意,時間戳16618336801661833710都是 GMT 時間,您可以查看 epochconverter.com

在此處輸入圖像描述

現在,當我在Godbolt Compiler Explorer上運行這個確切的代碼時,我得到了不同的結果:

18031
1661816160
1661834191
gmtoff:0

所以它現在告訴我,現在的差異是 5 小時。 這是因為它假設我經過的時間是倫敦時間:但現在倫敦時間是凌晨 4.41。

請注意,gmtoffset 現在為零,表示這台機器在倫敦(或將其時區設置為英國)。

因此,我認為在您的情況下正在發生的事情是您在 UTC-4(紐約?)的某個地方並登錄了英國的計算機或使用編譯器資源管理器作為我自己。

我有 windows 使用 bash.exe

$ /cygdrive/c/Windows/System32/tzutil.exe /s "Central America Standard Time"
$ date "+%a %d-%b-%Y %I:%M:%S %Z"
Tue 30-Aug-2022 01:10:01 CDT
$ /cygdrive/c/Windows/System32/tzutil.exe /g
Central America Standard Time
$ /cygdrive/c/Windows/System32/tzutil.exe /s "E. South America Standard Time"
$ date "+%a %d-%b-%Y %I:%M:%S %Z"
Tue 30-Aug-2022 01:10:48 CDT
$ ./a.out
Seconds: 6191
mktm   : 1661833680
timer  : 1661839871
gmtoff : -18000
$ tzutil /s "India Standard Time"
$ ./a.out
Seconds: 47632
mktm   : 1661792280
timer  : 1661839912
gmtoff : 19800

因此,a.out 的 output 會根據系統時序而變化,例如使用 TZ 環境變量(在面向 Linux 的操作系統)具有相同時序的來自兩個星系的兩個行星的方式。 我再次使用管理員權限將我的系統設置回 IST。

C:> C:\Windows\System32\tzutil.exe /g
India Standard Time

當 web 服務器/系統上的任何應用程序使用不同的 TZ/tzutil 位置更改時,同樣適用於系統/移動/外部應用程序(如 ATM/...)內部的瀏覽器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM