How to format NSDate using NSDateFormatter (iPhone Xcode Tutorial)
So, you’re making an iPhone (or iPad) app, and want to know how to format an NSDate in Cocoa? Formatting NSDate in Objective-C is actually not too difficult. Open up Xcode and let’s get’s cracking with some Objective-C goodness!
For those who just smash up Xcode, and get cracking with their iPhone applications – I’m putting the full source code of this tutorial right here at the top:
NSDate *myDate = [NSDate date]; NSDateFormatter *df = [NSDateFormatter new]; [df setDateFormat:@"EEEE dd MMMM, yyyy"]; self.someLabel.text = [df stringFromDate:myDate]; [df release];
Right, and now for those who want a bit more of an explanation of how to format an NSDate for your iPhone applications in Objective-C.
To begin, create a date variable:
NSDate *myDate = [NSDate date];
Nothing particularly difficult there – we now have the current date stored in myDate.
Now, Apple have made a nice class called NSDateFormatter that we can use to display our NSDate in our iPhone app in all kinds of wonderful ways… First we need to create a new NSDateFormatter:
NSDateFormatter *df = [NSDateFormatter new];
Then we need to set a format on our NSDateFormatter, which will be used to dictate the way our NSDate is displayed on our iPhone. Similar (but not the same) to how PHP’s date() function works, we can use a date pattern as specified at Unicode.org: http://unicode.org/reports/tr35/tr35-6.html#Date_Format_Patterns.
If you wanted to display the date like “Friday 25 March, 2011″ you would use the following call to your NSDateformatter (in the above example, we declared this as ‘df’):
[df setDateFormat:@"EEEE dd MMMM, yyyy"];
Ok, so our NSDateFormatter is all set up, now how do we actually get this applied to our NSDate? Simple, we just use the following:
That’s basically it, but don’t forget to release your NSDateFormatter, as we used ‘new’ earlier (same as alloc, init):
stringFromDate returns a NSString, so you can either assign this to a variable, or apply it directly to a UILabel, UITextField etc…