Convert date to format Day, date month year

时间:2019-04-16 22:35:27

标签: ios swift nsdateformatter

I'm trying to convert a date string from yyyy-MM-dd'T'HH:mm:ss.SSS'Z' to "day, date month year", something like this "Monday, 01 January 2018".

I'm using my helper function which converts a date string from one format to another. In the function below I'm not sure what parameter needs to be passed for to:

func convertDate(from inputFormat: String, to outputFormat: String) -> String {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = inputFormat
    if let dateInLocal = dateFormatter.date(from: self) {
        dateFormatter.dateFormat = outputFormat
        dateFormatter.amSymbol = "AM"
        dateFormatter.pmSymbol = "PM"
        return dateFormatter.string(from: dateInLocal)
    }
    return "NA"
}

Using above extension like below

dateAndName = date.convertDate(from:"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", to: "")

1 个答案:

答案 0 :(得分:1)

Refer to the documentation for date formats.

EEEE gives the full weekday name. MMMM gives the full month name. dd gives a two-digit month number. yyyy gives a four-digit year number.

Do not quote the Z in the input format. The Z in the date string represents the timezone of the date string. If you quote the Z in the date format then the Z is essentially ignored in the string as a timezone indicator and the date formatter will parse the date string as if it were local time and give you the wrong result.

Here's your cleaned up code:

func convertDate(from inputFormat: String, to outputFormat: String) -> String? {
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = inputFormat
    dateFormatter.local = Locale(identifier: "en_US_POSIX")

    if let dateInLocal = dateFormatter.date(from: self) {
        dateFormatter.dateFormat = outputFormat
        dateFormatter.locale = Locale.current
        return dateFormatter.string(from: dateInLocal)
    }

    return nil
}

dateAndName = date.convertDate(from:"yyyy-MM-dd'T'HH:mm:ss.SSSZ", to: "EEEE, dd MMMM yyyy")

Note that this function should return an optional string. Let the caller decided how to deal with invalid input.

Also note the special locale used to parse the input string.