简体   繁体   中英

Converting seconds to UNIX timestamp in C++

Here is my code that should display two full dates after being passed timestamps:

#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;
}

I'm doing something wrong with the conversion from seconds to time_t, as you can see by this output:

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

Mon Aug 23 20:11:40 2021

For reference:

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

You can't just cast a string pointer to a time_t. Use atol() to get a long from your string, and then cast that to a time_t.

The values you are getting back are the pointer arithmetic value interpreted as a time, or essentially random.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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