NSTimeInterval to HH:mm:ss?

后端 未结 12 1815
陌清茗
陌清茗 2020-12-04 08:53

If I have an NSTimeInterval that is set to say 200.0, is there a way to convert that into 00:03:20, I was thinking I could initialise an NSDate with it and then use NSDateFo

12条回答
  •  执念已碎
    2020-12-04 09:33

    Some extra lines of code, but I feel using NSDateComponents will give a more precise value.

    - (NSString *)getTimeRepresentationFromDate:(NSDate *)iDate withTimeInterval:(NSTimeInterval)iTimeInterval {
        NSString *aReturnValue = nil;
        NSDate *aNewDate = [iDate dateByAddingTimeInterval:iTimeInterval]; 
    
        unsigned int theUnits = NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
        NSCalendar *aCalender = [NSCalendar currentCalendar];
        NSDateComponents *aDateComponents = [aCalender components:theUnits fromDate:iDate toDate:aNewDate options:0];
    
        aReturnValue = [NSString stringWithFormat:@"%d:%d:%d", [aDateComponents hour], [aDateComponents minute], [aDateComponents second]];
    
        return aReturnValue;
    }
    

提交回复
热议问题