简体   繁体   English

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

[英]Comparing two timestamp strings in C++

I have two timestamps stored as string variables. 我有两个时间戳记存储为字符串变量。 The timestamps are in the format dd/mm/yyyy-hh:mm:ss I am trying to find the difference in seconds between the two timestamps (ignoring the dates). 时间戳格式为dd / mm / yyyy-hh:mm:ss我试图找出两个时间戳之间的秒数差异(忽略日期)。

(I haven't assigned strings to a and b but they hold a timestamp each) (我没有为a和b分配字符串,但是它们每个都有一个时间戳)

It always outputs 0 for the number of seconds difference and I can't work out why. 对于秒数差,它总是输出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;

Don't use hardcoded substring values (1 minute vs 11 minute might make you go off if 01 notation isn't used... and you have months ,days and hours also to take into account). 请勿使用硬编码的子字符串值(如果不使用01表示法,则1分钟vs 11分钟可能会让您失望……而且您还需要考虑几个月,几天和几小时)。

Instead of hardcoding the offset try to go after the unique characters (for you to get the "seconds" , take account the only the string after the 2nd occurrence of ":" ). 而不是硬编码偏移量,请尝试在唯一字符之后输入(为了获得“ seconds”,请考虑第二次出现“:”之后的唯一字符串)。

I suggest use CTime to work with timestamp. 我建议使用CTime与时间戳一起使用。

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

You can use this for storage and later, if you need, convert to string. 您可以将其用于存储,以后,如果需要,可以转换为字符串。

This would be a great reason to start with the Boost libraries, because Boost.Date_Time has exactly what you need. 这是从Boost库开始的一个很好的理由,因为Boost.Date_Time正是您需要的。 See the documentation about time durations . 请参阅有关持续时间的文档。

Here is an example program: 这是一个示例程序:

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

Output: 63 输出:63

Since you are already using substr and std::stoi , it should be easy for you to get the proper substrings from a and b to be passed to boost::posix_time::duration_from_string . 由于您已经在使用substrstd::stoi ,因此应该很容易从ab获取正确的子字符串,并将其传递给boost::posix_time::duration_from_string

Add following code after the defintions and before the assignments 在定义之后和分配之前添加以下代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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