skm
skm

Reputation: 5679

Difference between two timestamps in days C++

I have timestamps in the format (Year.Month.Day) in an XML file.

I need to find out the difference between two timestamps in days.

Sample Timestamps:

<Time Stamp="20181015">

<Time Stamp="20181012">

How can I find the number of days between the above timestamps?

Number of days = date2 - date1. I am considering all the days (don't need to skip weekends or any other day). Time-zone does not matter as well.

PS: I understand that I have to parse the timestamp from XML. I am stuck in the logic after parsing value.

Update-1: std::chrono::year and other such things are part of C++20. But I get a compilation error:

namespace "std::chrono" has no member "year"

Upvotes: 0

Views: 2513

Answers (2)

Howard Hinnant
Howard Hinnant

Reputation: 219588

You can use C++20's syntax today (with C++11/14/17) by downloading Howard Hinnant's free, open-source date/time library. Here is what the syntax would look like:

#include "date/date.h"
#include <iostream>
#include <sstream>

int
main()
{
    using namespace date;
    using namespace std;
    istringstream in{"<Time Stamp=\"20181015\">\n<Time Stamp=\"20181012\">"};
    const string fmt = " <Time Stamp=\"%Y%m%d\">";
    sys_days date1, date2;
    in >> parse(fmt, date1) >> parse(fmt, date2);
    cout << date2 - date1 << '\n';
    int diff = (date2 - date1).count();
    cout << diff << '\n';
}

This outputs:

-3d
-3

If you don't need time zone support (as in this example), then date.h is a single header, header-only library. Here is the full documentation.

If you need time zone support, that requires an additional library with a header and source: tz.h/tz.cpp. Here is the documentation for the time zone library.

Upvotes: 1

Galik
Galik

Reputation: 48665

There is the old fashioned way:

#include <ctime>
#include <iomanip> // std::get_time
#include <sstream>

// ... 

std::string s1 = "20181015";
std::string s2 = "20181012";

std::tm tmb{};

std::istringstream(s1) >> std::get_time(&tmb, "%Y%m%d");
auto t1 = std::mktime(&tmb);

std::istringstream(s2) >> std::get_time(&tmb, "%Y%m%d");
auto t2 = std::mktime(&tmb);

auto no_of_secs = long(std::difftime(t2, t1));

auto no_of_days = no_of_secs / (60 * 60 * 24);

std::cout << "days: " << no_of_days << '\n';

Upvotes: 1

Related Questions