Quick guide to iOS dateformatting

iOS SDK

This blogpost will focus on the setDateFormat: method of NSDateFormatter which allow us to define the date format of the textual representation of the date and time in iOS/Cocoa. Here’s a summary of the specifiers used in the date format string.

The most commonly used date format specifiers are (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)