-2

如何将两个时间戳与格式进行比较yyyy-mm-dd hh-mm-ss以获得分钟的总差异?

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

提前致谢!

编辑1:通过比较时间戳,我需要检查差异是否大于 x 分钟。

像:

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

difference = timestamp1 - timestamp2; //difference in minutes

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

3 回答 3

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

这是有效的,因为两个字符串的长度相同,并且数字按从最高有效到最低有效的顺序排列。

于 2013-02-01T13:03:15.340 回答
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. 
于 2013-02-01T13:08:11.143 回答
0

这可以通过提升来完成

#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.
于 2013-02-01T14:02:53.560 回答