【问题标题】:Converting seconds to UNIX timestamp in C++在 C++ 中将秒转换为 UNIX 时间戳
【发布时间】:2012-02-03 15:15:25
【问题描述】:

这是我的代码,应该在传递时间戳后显示两个完整日期:

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

我在从 seconds 到 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

【问题讨论】:

  • 如果这是家庭作业,应该这样标记
  • 这不是家庭作业。它出现在一个个人项目中。

标签: c++ date casting type-conversion unix-timestamp


【解决方案1】:

您不能只将字符串指针转换为 time_t。使用 atol() 从字符串中获取 long,然后将其转换为 time_t。

您返回的值是指针算术值,被解释为时间,或者本质上是随机的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 2014-03-07
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 1970-01-01
    • 2013-12-14
    相关资源
    最近更新 更多