objective-c 将 NSNumber (double) 值转换为时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1259028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert NSNumber (double) value into time
提问by phx
i try to convert a value like "898.171813964844" into 00:17:02 (hh:mm:ss).
我尝试将“898.171813964844”之类的值转换为 00:17:02 (hh:mm:ss)。
How can this be done in objective c?
如何在目标 c 中做到这一点?
Thanks for help!
感谢帮助!
回答by phx
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]);
回答by Volker Voecking
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:
假设您只对小时、分钟和秒感兴趣,并且输入值小于或等于 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];
回答by So Over It
I know the answer has already been accepted, but here is my response using NSDateFormatter and taking into account timezone (to your timezone hours [eg. GMT+4] being unexpectedly added @Ben)
我知道答案已经被接受,但这是我使用 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]]);
[side note]@phx: assuming 898.171813964844 is in seconds, this would represent 00:14:58 not 00:17:02.
[旁注]@phx:假设 898.171813964844 以秒为单位,这将代表 00:14:58 而不是 00:17:02。
回答by mouviciel
- Convert your NSNumber value to a NSTimeInterval with
-doubleValue - Convert your NSTimeInterval value to a NSDate with
+dateWithTimeIntervalSinceNow: - Convert your NSDate to a NSString with
-descriptionWithCalendarFormat:timeZone:locale:
- 将您的 NSNumber 值转换为 NSTimeInterval
-doubleValue - 将您的 NSTimeInterval 值转换为 NSDate
+dateWithTimeIntervalSinceNow: - 将您的 NSDate 转换为 NSString
-descriptionWithCalendarFormat:timeZone:locale:

