Reputation: 696
I cannot find a list of the format specifiers allowed in the template argument of DateFormatter.dateFormat(fromTemplate:options:locale:)
.
Does anyone know where Apple documents these specifiers?
Upvotes: 12
Views: 4584
Reputation: 696
I'll expand on the answer in the comment with some examples. For iOS 7 and later the format codes are here: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns. The table is too big to copy it all here but here's a few that helped me get started. See that link for all of the formats and explanations.
Here's a playground fragment that I found helpful to explore these.
import Foundation
let components = DateComponents(
calendar: Calendar(identifier: .gregorian),
timeZone: nil,
era: 1,
year: 1984,
month: 1,
day: 2,
hour: nil, minute: nil, second: nil,
nanosecond: nil, weekday: nil,
weekdayOrdinal: nil, quarter: nil,
weekOfMonth: nil, weekOfYear: nil,
yearForWeekOfYear: nil)
let aDate = Calendar(identifier: .gregorian).date(from: components)!
let en_US = Locale(identifier: "en_US")
var df = DateFormatter()
func formatdate(_ template: String) -> String {
let custom = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: en_US)
df.dateFormat = custom
return df.string(from: aDate)
}
formatdate("Mdyyyy") // "1/2/1984"
formatdate("yyyyMMdd") // "01/02/1984"
formatdate("yyyyMMMdd") // "Jan 02, 1984"
formatdate("yyyyMMMMdd") // "January 02, 1984"
formatdate("yyyyMMMMMdd") // "J 02, 1984"
formatdate("yyyyG") // "1984 AD"
formatdate("yyyyGGGG") // "1984 Anno Domini"
formatdate("yyyyMMMddE") // "Mon, Jan 02, 1984"
formatdate("yyyyMMMddEEEE") // "Monday, Jan 02, 1984"
formatdate("yyyyMMMddEEEEE") // "M, Jan 02, 1984"
formatdate("MdYYYY") // "1/2/1984"
formatdate("YYYYMMdd") // "01/02/1984"
formatdate("YYYYMMMdd") // "Jan 02, 1984"
formatdate("YYYYMMMMdd") // "January 02, 1984"
formatdate("YYYYMMMMMdd") // "J 02, 1984"
formatdate("YYYYG") // "1984 AD"
formatdate("YYYYGGGG") // "1984 Anno Domini"
formatdate("YYYYMMMddE") // "Mon, Jan 02, 1984"
formatdate("YYYYMMMddEEEE") // "Monday, Jan 02, 1984"
formatdate("YYYYMMMddEEEEE") // "M, Jan 02, 1984"
Upvotes: 18