Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert NSNumber (double) value into time

i try to convert a value like "898.171813964844" into 00:17:02 (hh:mm:ss).

How can this be done in objective c?

Thanks for help!

like image 303
phx Avatar asked Aug 11 '09 08:08

phx


3 Answers

Final solution:

NSNumber *time = [NSNumber numberWithDouble:([online_time doubleValue] - 3600)];
NSTimeInterval interval = [time doubleValue];    
NSDate *online = [NSDate date];
online = [NSDate dateWithTimeIntervalSince1970:interval];    
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"HH:mm:ss"];

NSLog(@"result: %@", [dateFormatter stringFromDate:online]);
like image 95
phx Avatar answered Oct 19 '22 16:10

phx


Assuming you are just interested in hours, minutes and seconds and that the input value is less or equal 86400 you could do something like this:

NSNumber *theDouble = [NSNumber numberWithDouble:898.171813964844];

int inputSeconds = [theDouble intValue];
int hours =  inputSeconds / 3600;
int minutes = ( inputSeconds - hours * 3600 ) / 60; 
int seconds = inputSeconds - hours * 3600 - minutes * 60; 

NSString *theTime = [NSString stringWithFormat:@"%.2d:%.2d:%.2d", hours, minutes, seconds];   
like image 45
Volker Voecking Avatar answered Oct 19 '22 18:10

Volker Voecking


I know the answer has already been accepted, but here is my response using NSDateFormatter and taking into account timezone (to your timezone hours [eg. GMT+4] being unexpectedly added @Ben)

    NSTimeInterval intervalValue = 898.171813964844;
    NSDateFormatter *hmsFormatter = [[NSDateFormatter alloc] init];
    [hmsFormatter setDateFormat:@"HH:mm:ss"];
    [hmsFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    NSLog(@"formatted date: %@", [hmsFormatter stringFromDate:[NSDate dateWithTimeIntervalSinceReferenceDate:intervalValue]]);

[side note] @phx: assuming 898.171813964844 is in seconds, this would represent 00:14:58 not 00:17:02.

like image 3
So Over It Avatar answered Oct 19 '22 17:10

So Over It