0

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 ?

Thomas Young
  • 186
  • 1
  • 2
  • 10
  • 1
    `Do we have to split it to 2 and then * 60 ?` Yes. – DeiDei Sep 12 '18 at 14:35
  • 1
    Check this out: https://stackoverflow.com/questions/11213326/how-to-convert-a-string-variable-containing-time-to-time-t-type-in-c – Nanev Sep 12 '18 at 14:36
  • 1
    @YSC I'm unsure about the dupe. There is no need at all to convert the string into a `time_t` to just have to do more math to convert it's hours and minutes into total minutes. We can do that directly from the sting like `((time[0] - '0') * 600) + ((time[1] - '0') * 60) + ((time[3] - '0') * 10) + (time[4] - '0')` – NathanOliver Sep 12 '18 at 14:48
  • That's true, it might answer OP's question, but it is no certainty. – YSC Sep 12 '18 at 14:51

3 Answers3

2

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:

  • No need to manually split the string
  • No need for manual conversion from hours to minutes
  • The result goes straight into the chrono type safe units
  • No need to dip down to the old C API
Howard Hinnant
  • 206,506
  • 52
  • 449
  • 577
1

You 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.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
1

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.

Klaus
  • 24,205
  • 7
  • 58
  • 113