0

I have a number, such as:

301

I want to convert to a time format: 00:05:01

My idea is let the 301/3600 to get the hour, (301%3600)/60 get the minute, and 301%60 get the second, I can get the format string, but if is there is a easy way to get that? Because I think this maybe not normal.

s-n-2
  • 405
  • 1
  • 6
  • 24

3 Answers3

0

I think your method is appropriate and normal.There is no need to add API like this ,cause it is simple and clear enough, apple cant do anything for us, of course, you can package it yourself.

Kakashi
  • 31
  • 6
0

Try this using NSDateFormatter

NSDate *lastUpdate = [[NSDate alloc] initWithTimeIntervalSince1970:301];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
dateFormatter.dateFormat = @"HH:mm:ss";
NSLog(@"date time: %@", [dateFormatter stringFromDate:lastUpdate]);
KKRocks
  • 8,222
  • 1
  • 18
  • 84
0

If you can live with 0:05:01 (no leading zero for hours) use (NS)DateComponentsFormatter:

Swift:

let number = 301
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.zeroFormattingBehavior = .pad
let result = formatter.string(from: TimeInterval(number))
print(result)

ObjC:

NSInteger number = 301;
NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
formatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
NSString *result = [formatter stringFromTimeInterval:(NSTimeInterval)number];
NSLog(@"%@", result);
vadian
  • 274,689
  • 30
  • 353
  • 361