Jens Bergvall
Jens Bergvall

Reputation: 1627

Converting numeric values in OBJC to values of time? (hours instead of percent of an hour)

I'm currently trying to convert xml values that represents two times.

example:

<from>960</from>
<to>975</to>

i store these 2 values into two doubles:

double From = from;
double To = to;

Now, if i do

From=From/60;
To=To/60;

and

NSString *fromString = [NSString stringWithFormat:@"%f",From];
NSString *toString = [NSString stringWithFormat:@"%f",To];

i thereafter smash these together to one string separated by " - " and NSLog the new string:

NSLog(@"New String: %@",FromToString);

The output: 16:00-16:25

Now, what i'm trying to accomplish here is for the FromToString to get the value 16:00 - 16:15

So, the question is how do i recalculate this to represent hours in 60minutes instead of percent of an hour? O_o

Upvotes: 1

Views: 104

Answers (2)

deleterOfWorlds
deleterOfWorlds

Reputation: 552

you will need two variables, something like

fromHours = floor(from/60);
fromMinues = from % 60;
NSString fromTime = [NSString stringWithFormat:"%02f:%02f", 
                                               fromHours, fromMinues);

and the same for the other variable.

Upvotes: 1

calimarkus
calimarkus

Reputation: 9977

So all you want is to have a double (eg. 9.5) converted to a string (in this case: 09:30), right?

You can do it like that:

// get hours
NSInteger hours = (int)floor(number);

// get minutes
NSInteger minutes = (int)floor((number-hours)*60);

// construct string
NSString* timeString = [NSString stringWithFormat: @"%02d:%02d", hours, minutes];

cheers (not tested though)

Upvotes: 1

Related Questions