时间戳之间的差异,以分钟为单位

时间:2013-02-01 12:54:09

标签: c++ time compare

如何比较格式为yyyy-mm-dd hh-mm-ss的两个时间戳以获得总分差(以分钟为单位)?

从MySQL检索时间戳。到目前为止,我已尝试使用time_t甚至分解整个字符串进行比较,但后者的问题是它无法识别天数的差异。

提前感谢!

EDIT1: 通过比较我需要检查差异是否大于x分钟的时间戳。

像:

timestamp1 = getTimestampFunction1();
timestamp2 = getTimestampFunction2();

difference = timestamp1 - timestamp2; //difference in minutes

if (difference > 60)
{
    do this;
}
else
{
    do that;
}  

3 个答案:

答案 0 :(得分:2)

你提到了两个/三个问题,目前尚不清楚这些是你的实际问题。

如果您只想比较您知道他们具有您提及的格式的日期,您可以进行简单的字符串比较:

const std::string A = "2012-11-11 01-01-59",
                  B = "2011-11-11 01-01-59";

if (A < B) {} // A lies before B
if (A > B) {} // A lies after B

这是有效的,因为两个字符串具有相同的长度,并且数字从最重要到最不重要排序。

答案 1 :(得分:0)

这样的事情怎么样:

char d1[] = "2013-02-01 12:56:09";
char d2[] = "2013-01-02 13:14:27";

char *parts1[6];
char *parts2[6];
char *p1, *p2;

for(int i = 0; i < 6; i++)
{
     parts1[i] = strtok_r(i?0:d1, "-: ", &p1);
     parts2[i] = strtok_r(i?0:d2, "-: ", &p2);
}

struct tm t1, t2;

t1.year = strtol(parts1[0], 0, NULL);
t1.month = strtol(parts1[1], 0, NULL);
t1.day = strtol(parts1[2], 0, NULL);

t1.hour = strtol(parts1[3], 0, NULL);
t1.hour = strtol(parts1[4], 0, NULL);
t1.hour = strtol(parts1[5], 0, NULL);

t2.year = strtol(parts2[0], 0, NULL);
t2.month = strtol(parts2[1], 0, NULL);
t2.day = strtol(parts2[2], 0, NULL);

t2.hour = strtol(parts2[3], 0, NULL);
t2.hour = strtol(parts2[4], 0, NULL);
t2.hour = strtol(parts2[5], 0, NULL);

time_t tt1, tt2;

tt1 = mktime(&t1);
tt2 = mktime(&t2);

double diff = difftime(tt1, tt2) / 60;  // Seconds -> make it minutes. 

答案 2 :(得分:0)

这可以通过boost

完成
#include <boost/date_time/local_time/local_time.hpp>

#include <string>
using namespace std;
using namespace boost::local_time;
using namespace boost::posix_time;

class DateTimeDiff {
    istringstream ss;
    local_time_input_facet* facet;
public:
    DateTimeDiff(char const * format)
    : facet(new local_time_input_facet(format)) {
        ss.imbue(locale(ss.getloc(), facet));
    }
    double delta_minutes( string t0, string t1 ) {
        local_date_time ldt0(not_a_date_time), ldt1(not_a_date_time);
        ss.str(t0); ss >> ldt0;
        ss.str(t1); ss >> ldt1;
        return time_duration(ldt1 - ldt0).total_seconds() / 60.0;
    }
};

int main() {
    DateTimeDiff dt("%Y-%m-%d %H-%M-%S");

    const string t0 = "2013-01-02 13-14-27",
                 t1 = "2013-02-01 12-56-09";

    double diff = dt.delta_minutes(t0,t1);

    cout << t0 << " and "
         << t1 << " are "
         << diff << " minutes apart."
         << endl;

    cout << diff << " minutes is ";
    if (diff > 60) {
        cout << "more than";
    } else {
        cout << "less than or equal to";
    }
    cout << " one hour." << endl;

    return 0;
}

输出

2013-Jan-02 13:14:27 UTC and 2013-Feb-01 12:56:09 UTC are 43181.7 minutes apart.
43181.7 minutes is more than one hour.