Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert an NSTimeInterval (seconds) into minutes

I've got an amount of seconds that passed from a certain event. It's stored in a NSTimeInterval data type.

I want to convert it into minutes and seconds.

For example I have: "326.4" seconds and I want to convert it into the following string: "5:26".

What is the best way to achieve this goal?

Thanks.

like image 369
Ilya Suzdalnitski Avatar asked Jul 27 '09 16:07

Ilya Suzdalnitski


People also ask

What is NSTimeInterval?

A NSTimeInterval value is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years. On its own, a time interval does not specify a unique point in time, or even a span between specific times.

How do you convert milliseconds to seconds in Swift?

To convert milliseconds to seconds, divide the number of milliseconds by 1000 and then call the Date(timeIntervalSince1970:) with the resulting seconds.


1 Answers

Brief Description

  1. The answer from Brian Ramsay is more convenient if you only want to convert to minutes.
  2. If you want Cocoa API do it for you and convert your NSTimeInterval not only to minutes but also to days, months, week, etc,... I think this is a more generic approach
  3. Use NSCalendar method:

    • (NSDateComponents *)components:(NSUInteger)unitFlags fromDate:(NSDate *)startingDate toDate:(NSDate *)resultDate options:(NSUInteger)opts

    • "Returns, as an NSDateComponents object using specified components, the difference between two supplied dates". From the API documentation.

  4. Create 2 NSDate whose difference is the NSTimeInterval you want to convert. (If your NSTimeInterval comes from comparing 2 NSDate you don't need to do this step, and you don't even need the NSTimeInterval).

  5. Get your quotes from NSDateComponents

Sample Code

// The time interval  NSTimeInterval theTimeInterval = 326.4;  // Get the system calendar NSCalendar *sysCalendar = [NSCalendar currentCalendar];  // Create the NSDates NSDate *date1 = [[NSDate alloc] init]; NSDate *date2 = [[NSDate alloc] initWithTimeInterval:theTimeInterval sinceDate:date1];   // Get conversion to months, days, hours, minutes unsigned int unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit | NSMonthCalendarUnit;  NSDateComponents *conversionInfo = [sysCalendar components:unitFlags fromDate:date1  toDate:date2  options:0];  NSLog(@"Conversion: %dmin %dhours %ddays %dmoths",[conversionInfo minute], [conversionInfo hour], [conversionInfo day], [conversionInfo month]);  [date1 release]; [date2 release]; 

Known issues

  • Too much for just a conversion, you are right, but that's how the API works.
  • My suggestion: if you get used to manage your time data using NSDate and NSCalendar, the API will do the hard work for you.
like image 150
Albaregar Avatar answered Sep 29 '22 08:09

Albaregar