Converting NSDate to NSString

Often we need to display a NSDate object on the screen with a specific format or by specific time zone. We can do this to the NSDate object easily.

Quick note for doing this is:
  1. Create NSDateFormatter object (e.g. dateFormatter)
  2. Call dateFormatter setDateFormat
  3. Call dateFormatter stringFromDate
Sample code
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:"yyyy-MM-dd 'at' HH:mm"];
NSString *dateDisplay = [dateFormatter stringFromDate:date];
NSLog(@"%@",dateDisplay); // 2012-02-08 at 18:30

To display AM / PM

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:"yyyy-MM-dd 'at' h:mm aaa"];
NSString *dateDisplay = [dateFormatter stringFromDate:date];
NSLog(@"%@",dateDisplay); // 2012-02-08 at 6:30 PM

You can also set the NSDateFormatter to a difference timezone. (You might want to do this if your app's data has different timezone setting)

NSTimeZone * currentDateTimeZone = [NSTimeZone localTimeZone]; // use [NSTimeZone systemTimeZone] to access iOS system timezone setting.
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:currentDateTimeZone];
[dateFormatter setDateFormat:"yyyy-MM-dd 'at' HH:mm"];


or by using buildin NSDateFormatter styles

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[NSLocale currentLocale]];
[dateFormatter setDateStyle:NSDateFormatterShortStyle];
[dateFormatter setTimeStyle:NSDateFormatterLongStyle];

There are still a lot that your can do then the above, for e.g. displaying timezone. But the above should get your started with converting date to string for display using NSDateFormatter.

Comments

  1. […] is often used in-conjunction with NSCalendar and NSDateComponents, converting a date to string for display on view is unavoidable; though they provide more functionality they tends to have high […]

    ReplyDelete

Post a Comment