使用c ++在两个日期到时间字符串之间获得差异

时间:2018-02-28 08:28:02

标签: c++ ctime time-t

我需要找到两个日期到时间段之间的差异,以秒为单位。这是我做的:使用sscanf分配日期和时间变量。将变量分配给struct tm对象(timeInfo)。

时间字符串示例:周四,2018年3月29日11:45:00

一切都按预期工作正常。现在出现了问题。我已经获得了该计划中显示的当前时间。但是当我获得currentTime时, tm_wday,tm_yday和tm_isdst 等成员被分配给它,而我所用的字符串并没有这些细节。我应该分配它们以获得差异秒吗?

有解决方法吗?

int GetDiffTimeInMilliseconds(LPCSTR expireValue)
{
const char monthNames[] =  "JanFebMarAprMayJunJulAugSepOctNovDec";
int hh,mm,ss,day,year,monthNumber;
char weekday[10],month[5],timezone[5];
struct tm timeInfo,currentTime;
time_t now;

sscanf(expireValue,"%[^,], %d %s %d %d:%d:%d %s",weekday,&day,month,&year,&hh,&mm,&ss,timezone);

cout<<weekday<<" "<<day<<" "<<month<<" "<<year<<" "<<hh<<":"<<mm<<":"<<ss;

monthNumber = (strstr(monthNames,month)-monthNames)/3;

timeInfo.tm_mday = day;
timeInfo.tm_mon = monthNumber;
timeInfo.tm_year = year - 1900;
timeInfo.tm_hour = hh;
timeInfo.tm_min = mm;
timeInfo.tm_sec = ss;

time(&now);
currentTime = *localtime(&now);

INT64 seconds= difftime(mktime(&timeInfo),now);

cout<<"The seconds are: "<<seconds;

}

3 个答案:

答案 0 :(得分:0)

试试这个:

time_t now;

time(&now);
struct tm *currentTime = localtime(&now);

答案 1 :(得分:0)

使用std::chrono

的解决方案
#include <chrono> //std::chrono
#include <iostream> //std::cout
#include <thread> //std::this_thread::sleep_for

auto get_dif_duration(const std::chrono::time_point<std::chrono::system_clock> & time_point)
{
    return std::chrono::system_clock::now() - time_point;
}

int main()
{

    using namespace std::chrono_literals;

    auto start = std::chrono::system_clock::now();

    std::this_thread::sleep_for(2s);

    auto seconds = std::chrono::duration_cast<std::chrono::seconds>(get_dif_duration(start));

    std::cout << "Waited: " << seconds.count() << " seconds\n";

}

答案 2 :(得分:0)

我做到了。这是我在给定时间和当前时间之间找到差异所做的更新代码。

日期时间字符串示例:周六,2018年3月31日09:41:28 GMT

INT64 GetDiffTimeInMilliseconds(LPCSTR expireValue)
{
const char monthNames[] =  "JanFebMarAprMayJunJulAugSepOctNovDec";
int hh,mm,ss,day,year,monthNumber;
char weekday[10],month[5],timezone[5];
struct tm timeInfo,currentTime;
time_t now;

time(&now);
currentTime = *localtime(&now);

sscanf(expireValue,"%3[^,], %d %s %d %d:%d:%d %s",weekday,&day,month,&year,&hh,&mm,&ss,timezone);

cout<<weekday<<" "<<day<<" "<<month<<" "<<year<<" "<<hh<<":"<<mm<<":"<<ss;

monthNumber = (strstr(monthNames,month)-monthNames)/3;

timeInfo.tm_mday = day;
timeInfo.tm_mon = monthNumber;
timeInfo.tm_year = year - 1900;
timeInfo.tm_hour = hh;
timeInfo.tm_min = mm;
timeInfo.tm_sec = ss;

INT64 seconds= difftime(mktime(&timeInfo),mktime(&currentTime));

cout<<"The seconds are : "<<seconds;

return seconds;

}