Helper method to convert an NSDate to string

February 26, 2013 in iOS Snippets

For performance reasons we only create the formatter object once, and just reuse it afterwards. The formatter style can be easily tailored by duplicating the method and changing its options; we keep the method’s name as descriptive as possible of the conversion to be done. It is also a good idea to keep this in a category on NSString.


+ (NSString*)dateAsFullDateTime:(NSDate*)date;
{
  static NSDateFormatter * formatter = nil;
  if (formatter == nil) {
    formatter = [[NSDateFormatter  alloc] init];
    [formatter setDateStyle:NSDateFormatterFullStyle];
    [formatter setTimeStyle:NSDateFormatterLongStyle];
    [formatter setDoesRelativeDateFormatting:NO];
  }
  return [formatter stringFromDate:date];
}