• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 6464
  • Last Modified:

NSTimeInterval to minutes and seconds

I have an integer in seconds, that when converted to minutes is less than 60 minutes (So no need to worry about hours). I want to convert the seconds string to a format like this:
int seconds = 352;

...

NSString *time = @"05:52";

NOTE: minutes must have the 0 in front of it if its less than 10 minutes. Same for seconds obviously :)

Max
0
TheMaximumWeasel
Asked:
TheMaximumWeasel
  • 3
  • 2
1 Solution
 
fridomCommented:
I guess you have to write something yourself, if you do not find a special class for handling that stuff. May be that OpenGroupware has support in that area.

Regards
Friedrich
#include <Foundation/Foundation.h>
 
NSString *secondsToMinutesAndSeconds(long seconds) {
  /* check that the seconds are less than a day */
  NSString *result;
  div_t minutesAndSeconds;
  if (seconds > 60 * 24 
     || seconds < 0) {
    NSLog(@"Time in seconds is is out of bounds\n");
    return nil;
 
  }
  minutesAndSeconds = div(seconds, 60);
  result = [NSString stringWithFormat: @"%0.2d:%0.2d", minutesAndSeconds.quot,
                     minutesAndSeconds.rem ];
  return result;
 
}
 
int
main(void)
{
  id pool = [[NSAutoreleasePool alloc] init];
  int seconds = 352;
  NSString *formatted_time = secondsToMinutesAndSeconds(seconds);
  
  NSLog(@"%d seconds are %@ (min:sec)\n", seconds, formatted_time);
 
  // The end...
  [pool release];
 
  return 0;
}

Open in new window

0
 
TheMaximumWeaselAuthor Commented:
Is it possible you could make that into a c function that uses no objects except for the NSString that is returned? I know the amount of seconds will not be over a day.
0
 
fridomCommented:
I can not see why that could be a requirement. You have to create the NSString somehow. So why not using is as I did? However you can use any C function like e.g

char formatted_string_buf[20];

sprintf("formatted_string_buf, "%0.2d:%02d", minutesAndSeconds.quot, minutesAndSeconds.rem);
then you create the NSString from the C buffer.

Regards
Friedrich
0
 
fridomCommented:
Ok, let me clarify it. You question was fully and AFAIKT correctly answered, now you can accept the solution or not. If you like to get another answer then state precicly what can and what can not be used, but in another question.

Friedrich
0
 
TheMaximumWeaselAuthor Commented:
Sorry about the slow response I hadn't got around to checking the question.
0

Featured Post

Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now