簡體   English   中英

在C ++中將秒轉換為UNIX時間戳

[英]Converting seconds to UNIX timestamp in C++

這是我的代碼,應該在傳遞時間戳后顯示兩個完整的日期:

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

using namespace std;

int main (int argc, char* argv[])
{

    time_t startTime_t = (time_t) argv[1];
    time_t endTime_t = (time_t) argv[2];

    cout << argv[1] << endl << argv[2] << endl;
    cout << startTime_t << endl << endTime_t << endl;

    string startTime = asctime(localtime(&startTime_t));
    string endTime = asctime(localtime(&endTime_t));

    cout << startTime << endl << endTime << endl;

    return 0;
}

從秒到time_t的轉換中,我做錯了,如您從此輸出可以看到的:

$ ./a 1325783860 1325791065
1325783860
1325791065
1629762852
1629763900
Mon Aug 23 19:54:12 2021

Mon Aug 23 20:11:40 2021

以供參考:

$ date -d @1325783860
Thu Jan  5 12:17:40 EST 2012

您不能只將字符串指針轉換為time_t。 使用atol()從字符串中獲取長整數,然后將其強制轉換為time_t。

您返回的值是解釋為時間或本質上隨機的指針算術值。

暫無
暫無

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

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