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 *stringTy开发者_如何学运维peCast = [[NSString alloc] initWithData:selected
encoding:NSUTF8StringEncoding];
From ,above snippet datePicker is an object of UIDatePickerController
.
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.
Use NSDateFormatter to convert NSDate objects to NSString objects. Type conversion is different from type casting.
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™.
The method you use requires NSData, not NSDate, that's why it doesn't work.
精彩评论