Last Updated: February 25, 2016
·
12.32K
· cybersamx

Quick Guide to Objective-C DateFormatting

The class NSDateFormatter allows us to define the date format of the textual representation of the date and time in iOS/Cocoa.

Below is a summary of the most commonly used specifiers used in the date format string (keep in mind that they are case sensitive):

  • y = year
  • Q = quarter
  • M = month
  • w = week of year
  • W = week of month
  • d = day of the month
  • D = day of year
  • E = day of week
  • a = period (AM or PM)
  • h = hour (1-12)
  • H = hour (0-23)
  • m = minute
  • s = second

In general, the number of characters in a specifier determine the size of date field. Let’s use an example to illustrate date formatting.

eg. Input date = 2011-05-01 Sunday

1-character = 1-digit/character number or word (if number/word can’t be 1 character long then abbreviation or fullname is displayed).

[dateFormatter setDateFormat:@"E, d M y"];  // Output: Sun, 1 5 2011

2-character = 2-digit/character number or word (if number/word can’t be 2 character long then abbreviation is displayed).

[dateFormatter setDateFormat:@"EE, dd MM yy"];  // Output: Sun, 01 05 11

3-character = 3-digit/character number or word, or abbreviation (generally).

[dateFormatter setDateFormat:@"EEE, ddd MMM yyy"];  // Output: Sun, 001 May 2011

4-character = full name (generally).

[dateFormatter setDateFormat:@"EEEE, dddd MMMM yyyy"];  // Output: Sunday, 0001 May 2011

Here’s the weird part though, if you specify 5 E’s, you get an rather unexpected output. You would think that the output date field would be longer than 1 character:

[dateFormatter setDateFormat:@"EEEEE, ddddd MMMMM yyyyy"];  // Output: S, 00001 M 2011

For date formatting, the following reference table has been very useful:

Date Field Symbol Table - UTS #35 Unicode Locale Data Markup Language

2 Responses
Add your response

As side note, to anyone who doesn't know, date formatters should be reused as much as possible. Also changing the date format is almost as costly as creating a new date formatter so it is often wise to create multiple instances with different date formats.

over 1 year ago ·

That's a good point. I usually instantiate NSDateFormatter as a static variable especially if I know that the date format is static and pre-defined.

NSString *getDateStringFromDate(NSDate *date) {
  static NSDateFormatter *dateFormatter = nil;
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
     dateFormatter = [[NSDateFormatter alloc] init];
     // Output: 2011-05-01 13:15:08
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
  });

   return [dateFormatter stringFromDate:date];
 }
over 1 year ago ·