繁体   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