Last Updated: September 09, 2019
·
1.341K
· treverp

Method to convert NSDate to NSString

When working with Core Data and NSDates, especially as a noob, it can be somewhat of a challenge on figuring out how to convert the NSDate into a realistic usable object. Below is a quick method I put together that I found to help with just that. Please feel free to comment / give feedback. If you know of a simpler way or a smarter way to go about this please speak up. Your knowledge is my gain! I hope this is of help

-(NSString *)desiredMethodName: (NSDate *)date {

NSDateComponents *components = [[NSCalendar currentCalendar]    components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:   [NSDate date]];
NSString *dateAsString = [NSString stringWithFormat:@"%d/%d/%d", [components month],  [components day], [components year]];

return dateAsString;

}

3 Responses
Add your response

You could also have a NSDateFormatter in the class and use "– stringFromDate:". Mind you, changing the format is almost as expensive as creating a new formatter so if you need multiple date formats create multiple formatters.

I haven't tested the difference between your method and NSDateFormatter so if someone has some free time I would also like to see how they compare.

over 1 year ago ·

it's good 。。。。

over 1 year ago ·

Just one more note regarding +[NSCalendar currentCalendar]. Although +[NSCalendar currentCalendar] is static method, it doesn't reuse one instance of calendar, but creates new instance over and over again. Apple recommendation is create calendar once and reuse it. In your particular case the calendar should be created outside of desiredMethodName: method.

Also, @mrnickbarker is right about NSDateFormatter. Apple recommends that each date format has it's own NSDateFormatter instance, and because initialization of NSDateFormatters is expansive and setDateFormat is also expensive, it should be cached. Create it once and use it over and over again.

over 1 year ago ·