user997112
user997112

Reputation: 30645

Get current number of hours and minutes using chrono::time_point

I have been trying to find an example using std::chrono which simply gets a chrono::time_point and extracts the number of hours and number of minutes as integers.

I have:

std::chrono::system_clock::time_point now = std::chrono::system_clock::now();

but I cannot find out how to then extract the hours and the minutes (since midnight)? I am looking for something like:

int hours = now.clock.hours();

Upvotes: 7

Views: 7360

Answers (2)

Howard Hinnant
Howard Hinnant

Reputation: 219345

Here is a free, open-source date library which will do this for you. Feel free to inspect the code if you want to know exactly how it is done. You can use it to get the current hours and minutes since midnight in the UTC timezone like this:

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

int
main()
{
    auto now = date::floor<std::chrono::minutes>(std::chrono::system_clock::now());
    auto dp = date::floor<date::days>(now);
    auto time = date::make_time(now - dp);
    int hours = time.hours().count();
    int minutes = time.minutes().count();
    std::cout.fill('0');
    std::cout << std::setw(2) << hours << ':' << std::setw(2) << minutes << '\n';
}

If you want the information in some other timezone, you will need this additional IANA time zone parser (or you can write your own timezone management system). The above code would be modified like so to get the hours and minutes since midnight in the local timezone:

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

int
main()
{
    auto zt = date::make_zoned(date::current_zone(),
                               std::chrono::system_clock::now());
    auto now = date::floor<std::chrono::minutes>(zt.get_local_time());
    auto dp = date::floor<date::days>(now);
    auto time = date::make_time(now - dp);
    int hours = time.hours().count();
    int minutes = time.minutes().count();
    std::cout.fill('0');
    std::cout << std::setw(2) << hours << ':' << std::setw(2) << minutes << '\n';
}

These libraries are available on github here:

https://github.com/HowardHinnant/date

Here is a video presentation of the date library:

https://www.youtube.com/watch?v=tzyGjOm8AKo

And here is a video presentation of the time zone library:

https://www.youtube.com/watch?v=Vwd3pduVGKY

Upvotes: 6

Some programmer dude
Some programmer dude

Reputation: 409442

The problem is that there isn't really any such functionality in the standard library. You have to convert the time point to a time_t and use the old functions to get a tm structure.

Upvotes: 7

Related Questions