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?
A formatter that converts between dates and their textual representations.
dateFormat(fromTemplate:options:locale:)Returns a localized date format string representing the given date format components arranged appropriately for the specified locale. iOS 4.0+ iPadOS 4.0+ macOS 10.6+ Mac Catalyst 13.1+ tvOS 9.0+ watchOS 2.0+
I solved my problem to the format yyyy-MM-dd'T'HH:mm:ss. SSS'Z' (e.g 2018-06-15T00:00:00.000Z) with this: func formatDate(date: String) -> String { let dateFormatterGet = DateFormatter() dateFormatterGet. dateFormat = "yyyy-MM-dd'T'HH:mm:ss.
en_US_POSIX was invented to refer to the C (or 'null') locale code used in POSIX libraries.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With