1

I want to convert a timestamp into a formatted time. The timestamp is a double value (e.g. timestamp = 41274.043) with reference date from 1.1.1900 00:00 and should return something like 02.01.2017 01:01.

I couldn't find anything about how to set the reference time properly. Any advice? To customize date I would use strftime(), STL is necessary...

BR

jtotheakob

jtotheakob
  • 33
  • 4

1 Answers1

0

Using Howard Hinnant's free, open source, header-only library it can be done like this:

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

std::chrono::system_clock::time_point
to_chrono_time_point(double d)
{
    using namespace std::chrono;
    using namespace date;
    using ddays = duration<double, days::period>;
    return sys_days{January/1/1900} + round<system_clock::duration>(ddays{d});
}

int
main()
{
    std::cout << date::format("%d.%m.%Y %H:%M\n", to_chrono_time_point(41274.043));
}

This simply converts the double into a chrono::duration with a representation of double and a period of days, then rounds that duration into a system_clock::duration, and finally adds that duration to 1.1.1900 00:00. The result is a std::chrono::system_clock::time_point.

The std::chrono::system_clock::time_point can be formatted with date::format from the same library as shown. The output of this program is:

02.01.2013 01:01
Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
  • Sorry for the late reply. Thanks Howard for your answer. So, am I understanding correctly that there is no STL header available at the moment? – jtotheakob Oct 07 '19 at 10:07
  • 1
    That is correct. Though this library has been voted into the draft C++20 standard. It will be in the header `` and `namespace std::chrono` instead of `"date.h"` and `date`. I do not know when your vendor will offer this C++20 feature, but I hope within about a year. – Howard Hinnant Oct 07 '19 at 13:19
  • Might be silly, but is there an explanation how to add your library in NetBeans8.2 (Windows10)? Couldn't find a useful description. Curiously, I managed to add Boost library a few months ago, but this time it won't run... – jtotheakob Oct 09 '19 at 12:54
  • 1
    I don't know anything about NetBeans. But date.h is header-only and known to work with recent versions of Visual Studio. Just include the header and it works. If you also need time zone support (tz.h), then there's also a source file that needs compiling. Detailed instructions (including Windows-specific) are here: https://howardhinnant.github.io/date/tz.html#Installation – Howard Hinnant Oct 09 '19 at 13:01