2010-09-10 137 views
0

我有一个双重0.27392,我知道它是上午6:34:27。这在Excel中很简单,但我无法让NSDateFormatter发挥它的魔力。如何将double转换为HH:MM:SS ObjectiveC

+0

这是一个奇怪的双倍时间。我认为存储为双打的日期只是从某个参考日期开始经过的秒数。如果是这样的话,那么你的双倍甚至不会是一秒钟,如果从早上6:34:27开始测量,它只能表示上午6:34:27 :-) – zoul 2010-09-10 07:48:54

+0

是的,存储为double的日期是NSTimeInterval,从给定参考日期开始的秒数。标准参考日期是“2001年1月1日,GMT”的第一个实例。 “1970年1月1日,格林威治标准时间”也用于.. – LarsJK 2010-09-10 08:08:24

回答

1

哦好吧,很棒的抓住zoul。

在这种情况下,我会做:

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]; 
+0

是的,这样更好,不要自己发明日期格式化的东西总是一个好主意(太容易错过)。 – zoul 2010-09-10 08:36:31

+0

两个正确的答案,我希望我可以给它,但我一直在寻找NSDateFormatter的答案。 – munchine 2010-09-10 08:51:08

2

啊,我明白了。这是自一天开始以来经过的小时数。在这种情况下:

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 

...等等。