两个日期之间的秒数差异? [英] Difference in seconds between two dates?

查看:45
本文介绍了两个日期之间的秒数差异?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题很简单,其他语言中有许多特定于 API 的方法,但我发现没有一个对于跨平台 C++ 使用来说是简单直接的.

The question is simple, there are many API specific methods in other languages, but I found none that that were simple and straight forward for Cross-platform C++ usage.

如果我有两个日期,并且假定它们在同一语言环境中,那么在 C++ 中区分它们的最简单方法是什么?

If I have two dates, and they are assumed to be in the same locale, what is the easiest way to differentiate them in C++?

我(有点)研究过使用 time.h,创建两个 tm 对象,将它们转换为 UTC,然后区分它们.

I have (somewhat) looked at using time.h, creating two tm objects, converting them to UTC and then differentiating them.

日期的当前格式为:YY/MM/DD HH:mm:SS(存储为单个整数)

The current format for the dates is: YY/MM/DD HH:mm:SS (stored as individual integers)

好的,根据当前的答案,我已经完成了以下操作(目前):

Ok, based on current answers, I've done the following (for now):

time_t calculate_seconds_between(
    const uint Y1, const uint M1, const uint D1, const uint H1, const uint m1, const uint S1, // YY/MM/DD HH:mm:SS
    const uint Y2, const uint M2, const uint D2, const uint H2, const uint m2, const uint S2
)
{
    time_t raw;
    time(&raw);

    struct tm t1 = *gmtime(&raw), t2 = t1;

    t1.tm_year = Y1 - 1900;
    t1.tm_mon = M1 - 1;
    t1.tm_mday = D1;
    t1.tm_hour = H1;
    t1.tm_min = m1;
    t1.tm_sec = S1;

    t2.tm_year = Y2 - 1900;
    t2.tm_mon = M2 - 1;
    t2.tm_mday = D2;
    t2.tm_hour = H2;
    t2.tm_min = m2;
    t2.tm_sec = S2;

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

    return (tt2 - tt1);
}

哪个效果很好.

推荐答案

要将 YY/MM/DD HH:mm:SS 转换为 struct tm 可以使用strptime(如果没有,请制作一个等价物)

To convert from YY/MM/DD HH:mm:SS to struct tm you can use strptime (or make an equivalent if you don't have it)

const char * dateInput;
// ....
struct tm tm;
time_t val;

memset(&tm, 0, sizeof(struct tm));
strptime(dateInput,"%y/%m/%d %H:%M:%S",&tm);
val = mktime(&tm);

获得两个 time_t 值后,您可以调用 difftime.

After you have the two time_t values you can call difftime.

这篇关于两个日期之间的秒数差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆