Objective c 将NSNumber(双精度)值转换为时间

Objective c 将NSNumber(双精度)值转换为时间,objective-c,nsnumber,Objective C,Nsnumber,我尝试将类似“898.171813964844”的值转换为00:17:02(hh:mm:ss) 在目标c中如何做到这一点 谢谢你的帮助 使用-doubleValue 将NSTimeInterval值转换为具有+dateWithTimeIntervalSinceNow: 使用将NSDate转换为NSString-descriptionWithCalendarFormat:timeZone:locale: 假设您只对小时、分钟和秒感兴趣,并且输入值小于或等于86400,则可以执行以下操作: NSNu

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

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

谢谢你的帮助

  • 使用
    -doubleValue
  • 将NSTimeInterval值转换为具有
    +dateWithTimeIntervalSinceNow:

  • 使用
    将NSDate转换为NSString-descriptionWithCalendarFormat:timeZone:locale:

  • 假设您只对小时、分钟和秒感兴趣,并且输入值小于或等于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];   
    
    最终解决方案:

    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]);
    

    我知道答案已经被接受,但下面是我使用NSDateFormatter并考虑时区的回复(您的时区时间[例如GMT+4]意外添加到@Ben)


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

    您可以使用简单的算术,但我不知道898.171813964844是如何表示00:17:02的。浮点数指的是什么?嘿,在ruby中,我简单地执行Time.at(Time-3600).strftime(“%H:%M:%S”),并得到正确的结果。(时间是浮点值)NSTimeInterval interval=[time doubleValue];NSDate*日期=[NSDate日期];日期=[NSDate date WITHTIMEINTERVALICENCENOW:interval];NSString*值=[date descriptionWithCalendarFormat:@“%I:%M:%S”时区:[NSTimeZone localTimeZone]区域设置:nil];这样地?但我明白了:警告NSDate可能不会响应-descriptionWithCalendarFormat…将NSDate转换为字符串的非弃用方式(或iPhone SDK方式)是使用NSDateFormatter。此外,您是否尝试将数字转换为绝对时间(即时间戳?)或单位(即数字是否仅为秒数?)?无需考虑,我错过了你上面的评论。使用NSDateFormatter.-descriptionWithCalendarFormat。。。在iPhone上不可用。正如Wevah所建议的那样,改用NSDateFormatter。当我的时间间隔中有94.000的值时,为什么会得到8小时1分34秒?我做错什么了吗?@Ben-这可能是因为你的时区是+8小时。尝试将时区设置为GMT
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]此解决方案不是最好的。我刚从斯洛伐克搬到布宜诺斯艾利斯,即使我使用了@Ben提到的技巧,我仍然得到了错误的转换。通常,当iPhone中的“设置/日期和时间/自动设置”处于关闭状态时,此功能在所有情况下都有效。
    
        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]]);