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
source share