1

I am trying to find some utility in the chrono namespace to provide to my application the same feature I had in my C# program. What I need to do is to compute the time difference between to specific dates, but I can't find anything this specific. For example following is my C# code:

var startDate = new DateTime(2000, 1, 1);
int diffDays = (DateTime.Today.Date - startDate.Date).Days;

return diffDays.ToString();

Is there any equivalent function in C++?

Nick
  • 10,309
  • 21
  • 97
  • 201

2 Answers2

4
// system_clock::from_time_t
#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>

int main ()
{
  using namespace std::chrono;

  // create tm with 1/1/2000:
  std::tm timeinfo = std::tm();
  timeinfo.tm_year = 100;   // year: 2000
  timeinfo.tm_mon = 0;      // month: january
  timeinfo.tm_mday = 1;     // day: 1st
  std::time_t tt = std::mktime (&timeinfo);

  system_clock::time_point tp = system_clock::from_time_t (tt);
  system_clock::duration d = system_clock::now() - tp;

  // convert to number of days:
  typedef duration<int,std::ratio<60*60*24>> days_type;
  days_type ndays = duration_cast<days_type> (d);

  // display result:
  std::cout << ndays.count() << " days have passed since 1/1/2000";
  std::cout << std::endl;

  return 0;
}

Credits: http://www.cplusplus.com/reference/chrono/system_clock/from_time_t/

gliderkite
  • 8,828
  • 6
  • 44
  • 80
2

Here's an easier way to do this using this header-only open source lib:

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

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto startDate = 2000_y/jan/1;
    auto diffDays = floor<days>(system_clock::now()) - sys_days{startDate};
    std::cout << diffDays.count() << '\n';
}

Currently outputs:

6138

Here is a wandbox link where you can paste the above code and try it out yourself using various versions of gcc and clang.

Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577