views:

40

answers:

2

I've got a double 0.27392 and I know it is 6:34:27 AM. This is simple in Excel, but I can't get NSDateFormatter to work its magic.

+2  A: 

Ah, I see. That’s the number of hours elapsed since the start of the day. In that case:

double time = 0.27392;
double timeInHours = time*24; // 6.57408
int hours = (int) timeInHours; // 6
int minutes = (timeInHours - floor(timeInHours)) * 60; // 0.57408*60=34.4448 → 34

…and so on.

zoul
+1  A: 

Oh OK, great catch zoul.

In that case i would do:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
[dateFormatter setDateStyle:NSDateFormatterNoStyle];

double time = 0.27392;
double timeInSeconds = time*24*60*60; // 0.27392 * 24 = 6.57408 hours *60 for minutes * 60 for seconds

NSDate *date = [NSDate dateWithTimeIntervalSinceReferenceDate:timeInSeconds]; //Creates a date: 1 January 2001 6:34:27 AM, GMT

NSLog(@"Time: %@", [dateFormatter stringFromDate:date]);
[dateFormatter release];
Larsaronen
Yes, that’s better, it’s always a good idea not to invent the date formatting stuff yourself (too easy to miss something).
zoul
Both correct answers and I wish I can give it to both, but I was looking for the NSDateFormatter answer.
munchine