views:

1946

answers:

3

Hey all,

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!

A: 
  1. Convert your NSNumber value to a NSTimeInterval with -doubleValue
  2. Convert your NSTimeInterval value to a NSDate with +dateWithTimeIntervalSinceNow:
  3. Convert your NSDate to a NSString with -descriptionWithCalendarFormat:timeZone:locale:
mouviciel
NSTimeInterval interval = [time doubleValue]; NSDate *date = [NSDate date]; date = [NSDate dateWithTimeIntervalSinceNow:interval]; NSString *value = [date descriptionWithCalendarFormat:@"%I:%M:%S" timeZone:[NSTimeZone localTimeZone] locale:nil]; like this? But i get: warning NSDate may not respond to -descriptionWithCalendarFormat....
phx
The non-deprecated way (or iPhone SDK way) of converting an NSDate to a string is to use an NSDateFormatter.
Wevah
Also, are you trying to convert the number into an absolute time (i.e., is it a timestamp?) or units (i.e., is the number just an amount of seconds?)?
Wevah
Nevermind, I missed your comment up above. Use an NSDateFormatter.
Wevah
-descriptionWithCalendarFormat... is not available on iPhone. Use an NSDateFormatter instead, as suggested by Wevah.
mouviciel
+1  A: 

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];
Volker Voecking
+1  A: 

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]);
phx
Why do I get something like 8 hours 1 minutes and 34 seconds when I have the value 94.000 in my interval? Am I doing something wrong?
Ben