Does there has any easy way to convert "02:00" to minutes say 120 ?
Do we have to split it to 2 and then * 60 ?
Does there has any easy way to convert "02:00" to minutes say 120 ?
Do we have to split it to 2 and then * 60 ?
Here's how to do it using Howard Hinnant's date/time library:
#include "date/date.h"
#include <cassert>
#include <iostream>
#include <sstream>
int
main()
{
using namespace date;
using namespace std;
using namespace std::chrono;
istringstream in{"02:00"};
minutes m;
in >> parse("%H:%M", m);
assert(m == 120min);
}
Additionally this should port to the upcoming C++20 spec by simply removing #include "date/date.h"
and using namespace date;
.
The advantage of this technique includes:
chrono
type safe unitsYou don't need to split anything here. In "12:34"
the 1
represents the tens of hours, the 2
is how many single hours, the 3
is the tens of minutes and the 4
is the single minutes. Knowing that you can multiply each position by how many minutes it represents.
If we have
std::sting time = "12:34"
then (time[0] - '0') * 600
would give use 600 minutes (time[0] - '0'
converts the character '1'
to the number 1
). (time[1] - '0') * 60
would be 120 more minutes. If we keep going we'd have
((time[0] - '0') * 600) + ((time[1] - '0') * 60) + ((time[3] - '0') * 10) + (time[4] - '0')
And all of that added up gives use 754 minutes. You can put that into a function if you have to do it multiple times.
Maybe you like this one:
std::tm tm = {};
std::stringstream ss("20:05");
ss >> std::get_time(&tm, "%H:%M");
std::cout << tm.tm_hour * 60 + tm.tm_min << std::endl;
Maybe it is much to much overhead using this big library calls in your case, but maybe you have to deal with more complex time strings.