Search code examples
swiftnsdateformatter

How to format date with DateFormatter that includes friendly day and month


How can I format a date that includes a friendly day and month literal such as:

"Thursday, June 14, 2018"

Day can be:

Sunday, Monday, Tuesday, Wedenesday, Thursday, Friday, Saturday, Friday

Month can be:

January, February, March, April, May, June, July, August, September, October, November, December

let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.date(from: "Thursday, June 14, 2018")

What should the format be set to?

Something like this?

static let format = "DAY, MONTH, dd, YYYY"

Is it even possible to do this with DateFormatter() ?


Solution

  • Use EEEE for the full weekday name and MMMM for the full month name. But since you are parsing fixed formatted strings that are in English, you must also set the formatter's locale to en_US_POSIX.

    let formatter = DateFormatter()
    formatter.dateFormat = "EEEE, MMMM d, yyyy"
    formatter.locale = Locale(identifier: "en_US_POSIX")
    return formatter.date(from: "Thursday, June 14, 2018")
    

    Note that this will treat the date as being in the user's local timezone.

    See the full specification for all possible date formatting patterns.