views:

52

answers:

3

Hello all,

I am new in iphone development. I have a issue. I want to convert a NSTimeInterval value in NSString, but not success in this. please a quick look on below code.

in .h

NSTimeInterval startTime;
NSTimeInterval stopTime;
NSTimeInterval duration;

in .m

startTime = [NSDate timeIntervalSinceReferenceDate];
stopTime = [NSDate timeIntervalSinceReferenceDate];

duration = stopTime-startTime;

NSLog(@"Duration is %@",[NSDate dateWithTimeIntervalSinceReferenceDate: duration]);
NSLog(@"Duration is %@", [NSString stringWithFormat:@"%f", duration]);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];

NSString *time = [dateFormatter stringFromDate:duration];----> Error
[dateFormatter release];

And on one label set this string----

[timeLabel setText:time];

but it not works it shows error: incompatible type for argument 1 of 'stringFromDate:'

and if i comment that line it shows the right duration in console window.

thanks for any help.

+2  A: 

NSTimeInterval is actually a double, so to convert it to a string you should just use

NSString *time = [NSString stringWithFormat:@"%f", duration];
Vladimir
Thanks, this is really i want, and i have solved my problem.
singhSan
A: 
NSString *time = [dateFormatter stringFromDate:duration];----> Error

This duration is not class NSDate, so It can not be converted by this method named stringFromDate. As Vladimir said, NSTimeInterval is double, with his method you can get the right NSString.

Toro
A: 

From the NSDateFormatter class reference:

- (NSString *)stringFromDate:(NSDate *)date
                              ^^^^^^^^ the type of the argument

From your code:

NSTimeInterval duration; 
^^^^^^^^^^^^^^ the type of what you are passing.

The error says "incompatible type". What do you think that means? Perhaps NSTimeInterval is not compatible with NSDate*. Here is what the docs say about NSTimeInterval:

typedef double NSTimeInterval;

NSTimeInterval is always specified in seconds...

The error is telling you the compiler can't convert an NSTimeInterval (which is really a double) into a pointer to an NSDate. This is not surprising really. Since an NSTimeInterval is really a double, you can convert it into a string easily by using the %f format specifier.

foo = [NSString stringWithFormat: @"%f", timeInterval];
JeremyP
Thanks All, for quick response. by u suggestions i have understand that i am going to pass a different argument type. Now its work fine.Again Thanks Vladimir,Toro and JeremyP.
singhSan