16

我尝试将“898.171813964844”之类的值转换为 00:17:02 (hh:mm:ss)。

如何在目标 c 中做到这一点?

感谢帮助!

4

4 回答 4

31

最终解决方案:

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]);
于 2009-08-12T17:32:41.720 回答
9

假设您只对小时、分钟和秒感兴趣,并且输入值小于或等于 86400,您可以执行以下操作:

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];   
于 2009-08-11T11:25:33.803 回答
3

我知道答案已经被接受,但这是我使用 NSDateFormatter 并考虑到时区的回复(到您的时区时间 [例如 GMT+4] 被意外添加@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]]);

[旁注] @phx:假设 898.171813964844 以秒为单位,这将表示 00:14:58 而不是 00:17:02。

于 2012-06-23T05:10:09.950 回答
1
  1. 将您的 NSNumber 值转换为 NSTimeInterval-doubleValue
  2. 将您的 NSTimeInterval 值转换为 NSDate+dateWithTimeIntervalSinceNow:
  3. 将您的 NSDate 转换为 NSString-descriptionWithCalendarFormat:timeZone:locale:
于 2009-08-11T08:36:51.577 回答