比较C ++中的两个时间戳字符串

时间:2014-03-21 19:55:49

标签: c++ difference

我有两个时间戳存储为字符串变量。时间戳的格式为dd / mm / yyyy-hh:mm:ss 我试图找出两个时间戳之间的差异(忽略日期)。

(我还没有为a和b分配字符串,但每个字符都有一个时间戳)

它总是输出0表示秒数的差异,我无法解决原因。

std::string a, b; // hold timestamps
struct tm t, t1;
double seconds;

t.tm_hour = stoi(a.substr(11,2)); // stoi() cast substring to int
t.tm_min = stoi(a.substr(14,2));
t.tm_sec = stoi(a.substr(17,2));

t1.tm_hour = stoi(b.substr(11,2));
t1.tm_min = stoi(b.substr(14,2));
t1.tm_sec = stoi(b.substr(17,2));

seconds = difftime(mktime(&t1), mktime(&t));
std::cout<<seconds;

4 个答案:

答案 0 :(得分:1)

不要使用硬编码的子字符串值(如果没有使用01表示法,1分钟对11分钟可能会让你离开...而且你还需要数月,日和时间来考虑)。

不是硬编码偏移量,而是尝试追踪唯一字符(为了获得&#34;秒&#34;,在第二次出现&#34之后考虑唯一的字符串;&#34; )。

答案 1 :(得分:0)

我建议使用CTime来处理时间戳。

http://www.cplusplus.com/reference/ctime/

您可以将其用于存储,如果需要,可以将其转换为字符串。

答案 2 :(得分:0)

这是从Boost库开始的一个很好的理由,因为Boost.Date_Time正是您所需要的。请参阅有关time durations

的文档

以下是一个示例程序:

#include <boost/date_time/posix_time/posix_time.hpp>
#include <iostream>

int main()
{
    boost::posix_time::time_duration duration1 = boost::posix_time::duration_from_string("10:11:12");
    boost::posix_time::time_duration duration2 = boost::posix_time::duration_from_string("10:12:15");

    std::cout << (duration2 - duration1).total_seconds() << "\n";
}

输出:63

由于您已经在使用substrstd::stoi,因此您可以轻松地将ab的正确子字符串传递给{{1 }}

答案 3 :(得分:0)

在定义之后和作业之前添加以下代码

// initialize time structures with all the details for 'now'
time_t ts;
time( &ts );
t = * localtime( &ts );
t1 = t;