Get current hours and minutes using chrono :: time_point

I am trying to find an example using std :: chrono, which simply gets chrono::time_point and allocates 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 canโ€™t find out how to extract hours and minutes from it (from midnight)? I am looking for something like:

 int hours = now.clock.hours(); 
+5
source share
2 answers

The problem is that the standard library does not have such functionality. You must convert the time point to time_t and use the old functions to get the tm structure .

+4
source

Here is a free, open source date library that does it for you. Feel free to check the code if you want to know exactly how to do it. You can use it to get the current hours and minutes since midnight in the UTC time zone as follows:

 #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 need information in a different time zone, you will need this additional IANA time zone analyzer (or you can write your own time zone management system). The above code will be modified to get hours and minutes from midnight in the local time zone:

 #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

+6
source

Source: https://habr.com/ru/post/1239479/


All Articles