30

How to covert the NSTimeInterval to NSString? I have

NSTimeInterval  today = [[NSDate date] timeIntervalSince1970];

I have to give "today" as input as NSString.

halfer
  • 19,824
  • 17
  • 99
  • 186
Warrior
  • 39,156
  • 44
  • 139
  • 214

2 Answers2

79

NSTimeInterval is just a double type so you can convert it to string using +stringWithFormat: method

NSTimeInterval  today = [[NSDate date] timeIntervalSince1970];
NSString *intervalString = [NSString stringWithFormat:@"%f", today];
Vladimir
  • 170,431
  • 36
  • 387
  • 313
  • Thanks ,i was trying with %@ instead of %f. – Warrior Nov 25 '10 at 14:42
  • 2
    %@ is only for objects. And moreover, objects that respond to the `-description` message. – jer Nov 25 '10 at 14:43
  • @jer, or localizedDescription it seems... anyway description method is defined in NSObject so all its descendants respond to it – Vladimir Nov 25 '10 at 14:45
  • All descendents of NSObject do yes, but descendents of NSProxy do not. Sorry, I wasn't being explicit. – jer Nov 25 '10 at 14:52
  • actually you made a good point - as most classes inherit from NSObject and respond to -description: method it is so easy to lose care and accidentally call it on those objects which do not respond – Vladimir Nov 25 '10 at 15:29
  • What's the point of typedefing NSTimeInterval if I have to know what it stands for to log the value of this type. It looks like a breach in abstraction to me. Isn't there a truly platform-independent way to deal with typedefs? – Alexei Sholik Feb 04 '11 at 10:50
3
-(NSString*)formattedDuration:(NSTimeInterval)interval{
    NSDateComponentsFormatter *formatter = [[NSDateComponentsFormatter alloc] init];
    formatter.allowedUnits = NSCalendarUnitHour | NSCalendarUnitMinute;
    formatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad;
    NSString *string = [formatter stringFromTimeInterval:interval];
    NSLog(@"%@", string);
    // output: 0:20:34
    return string;
}
Ofir Malachi
  • 1,145
  • 14
  • 20