views:

102

answers:

4

Hi, I developing an application, in which i found a ridiculous problem in type casting, I am not able to type cast NSDate to NSString.

NSDate *selected =[datePicker date];
NSString *stringTypeCast = [[NSString alloc] initWithData:selected
                                       encoding:NSUTF8StringEncoding];

From ,above snippet datePicker is an object of UIDatePickerController.

+5  A: 

One method would be:

NSString *dateString = [NSString stringWithString:[selected description]]

See the documentation.

Another would be:

NSString *dateString = [NSString stringWithFormat:@"%@", selected]

See the documentation.

A more appropriate method would be:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *dateString = [dateFormatter stringFromDate:selected];
[dateFormatter release];

This will automatically return the date in a string formatted to the user's local date format. See the documentation.

jsumners
Here i am usingNSString *dateString = [NSString stringWithFormat:@"%@", selected];but i am able to get the date into string with time attached , now i just want date not time so how do i do that plz suggest me for that, And thanks for the solution...
Prash.......
That is functionally equivalent to the first method I mentioned. In other words, you are only going to get back what the `description` method of the NSDate object is written to return. If you want a specific format then you need to use an NSDateFormatter and specify the desired format string.
jsumners
+2  A: 

You don't want to do this. What you really want to do is to use an NSDateFormatter to properly convert the NSDate into an NSString. Going about this any other way is Not Correct™.

Dave DeLong
+4  A: 

Use NSDateFormatter to convert NSDate objects to NSString objects. Type conversion is different from type casting.

progrmr
A: 

The method you use requires NSData, not NSDate, that's why it doesn't work.

Georg