Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c++11

chrono

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();
like image 468
user997112 Avatar asked Dec 30 '15 10:12

user997112


2 Answers

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

like image 115
Howard Hinnant Avatar answered Nov 14 '22 22:11

Howard Hinnant


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.

like image 31
Some programmer dude Avatar answered Nov 14 '22 23:11

Some programmer dude