Click to See Complete Forum and Search --> : Converting a time in string format to minutes
ae_jester
Nov 20th, 2002, 08:05 PM
I'm using C++ Builder 6
I'm trying to convert a string in the form "12:25", which represents a time of day, to minutes. So in this case "12:25" would become 745.
I've never done anything like this, and I can't seem to get anything working. I'm sure its something extremely simple.
I also need to convert a time in minutes to a time string, so 745 minutes would return "12:25", but I will attemp to do this part myself provided someone can assist me with the first part.
Thanx for any help!
HairyDave
Nov 21st, 2002, 02:59 AM
I don't know if there's an easier way, but couldn't you:
1. Tokenise the string (using strtok or other) to be an hours string and a minutes string.
2. Convert both to integers (atoi or other).
3. ( hours * 60 ) + minutes = total
Is that what you're looking for - or were you looking for something at a higher level?
HD
parksie
Nov 21st, 2002, 04:42 AM
If you know it's only going to be in the form "hh:mm" (including leading zeros, and 24-hour clock), you can do this:inline char down(char c) { return c - '0'; }
// ...
string dt = "23:12";
int minutes = down(dt[0]) * 10 * 60;
minutes += down(dt[1]) * 60;
minutes += down(dt[3]) * 10;
minutes += down(dt[4]);...or similar. I wouldn't *really* recommend that, since it has no error checking whatsoever. I'll leave that as an exercise for the reader ;)
kedaman
Nov 21st, 2002, 04:58 AM
or maybe something like this
int minutes = (dt[0]*10+dt[1])*60+dt[3]*10+dt[4]-0x7DD0;
:p
parksie
Nov 21st, 2002, 05:26 AM
Heh. You win ;)
CornedBee
Nov 22nd, 2002, 07:50 AM
Other way round is even easier:
C:
void minstotime(int mins, char *buffer) {
sprintf(buffer, "%02i:%02i", mins/60, mins%60);
}
C++:
void minstotime(int mins, string &str) {
ostringstream oss;
oss << setw(2) << setfill('0') << mins/60;
oss << ':';
oss << setw(2) << setfill('0') << mins%60;
str = oss.str();
}
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.