Frage

Is there a C++11 version of matlabs datenum function in #include<chrono>?

I already know it exists in boost thanks to this post

War es hilfreich?

Lösung

No, there is not. However here is a "how-to" manual for how to write the algorithms for your chrono-compatible date library. Using these algorithms, I can easily, for example, do this:

#include "../date_performance/date_algorithms"
#include <ratio>
#include <chrono>
#include <iostream>

typedef std::chrono::duration
        <
            int,
            std::ratio_multiply<std::ratio<24>, std::chrono::hours::period>
        > days;

typedef std::chrono::time_point<std::chrono::system_clock, days> date_point;

int
main()
{
    using namespace std::chrono;
    date_point datenum{days{days_from_civil(2014, 2, 5)}};
    auto d = system_clock::now() - datenum;
    auto h = duration_cast<hours>(d);
    d -= h;
    auto m = duration_cast<minutes>(d);
    std::cout << "The current UTC time is "  << h.count() << ':' << m.count() << '\n';
    date_point datenum2{days{days_from_civil(2014, 3, 5)}};
    std::cout << "There are " << (datenum2-datenum).count() << " days between 2014-03-05 and 2014-02-05\n";
}

Which for me outputs:

The current UTC time is 22:12
There are 28 days between 2014-03-05 and 2014-02-05

The first thing you need to do is create a chrono::duration to represent a day, named days above. Then it is handy to create a chrono::time_point based on the days duration. This time_point is compatible with every known implementation of system_clock::time_point. I.e. you can subtract them.

In this duration I subtract now() from the current date to get the hours::minutes of the day in the UTC timezone. I also demonstrate how to compute the number of days between any two dates.

Feel free to use these algorithms, and perhaps wrap all of this up in a type-safe date class. The link only provides the algorithms, and not an actual date class.

I might post a date class based on these algorithms in the future if I get the time...

Andere Tipps

I don't know what matlabs datenum is but here is how to do basically the same as the accepted answer of the question you link to, that is arithmetic with time points and durations but in C++11 without boost:

#include <chrono>
#include <iostream>
using namespace std;
using namespace std::chrono;

int main() {
    duration<long> one_day{ hours(24) };
    system_clock::time_point now = system_clock::now();
    system_clock::time_point tomorrow = now + one_day;
    time_t t = system_clock::to_time_t(tomorrow);
    cout << "Tomorrow: " << ctime(&t) << '\n';
}

Hope this helps.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top