Convert NSNumber (double) value into time

守給你的承諾、 提交于 2019-11-28 20:32:33

问题


i try to convert a value like "898.171813964844" into 00:17:02 (hh:mm:ss).

How can this be done in objective c?

Thanks for help!


回答1:


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



回答2:


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:

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



回答3:


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)

    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.




回答4:


  1. Convert your NSNumber value to a NSTimeInterval with -doubleValue
  2. Convert your NSTimeInterval value to a NSDate with +dateWithTimeIntervalSinceNow:
  3. Convert your NSDate to a NSString with -descriptionWithCalendarFormat:timeZone:locale:


来源:https://stackoverflow.com/questions/1259028/convert-nsnumber-double-value-into-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!