Converting a String to a Date in Swift [duplicate]

2019-05-27 02:45发布

问题:

This question already has an answer here:

  • Date does not appear in UILabel 2 answers

I have date in string with format below code want to change in Date but i'm getting nil

let addedDate = "Tue, 25 May 2010 12:53:58 +0000"
let formatter = DateFormatter()
formatter.dateFormat = "dd MM YYYY"
let date1 = formatter.date(from: addedDate)
print("DATE \(date1)")

回答1:

The date format needs to be for the string you are trying to convert, not the format you want back

so

formatter.dateFormat = "dd MM YYYY"

should be

formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"


回答2:

You have to transform your String (addedDateString) to a Date? (addedDate) then you can convert it to a String (dateString) using the format you want. Please note: addedDate is nil when conversion from String to Date failed.

import UIKit

let addedDateString = "Tue, 25 May 2010 12:53:58 +0000"

// Transform addedDateString to Date
let addedDateFormatter = DateFormatter()
addedDateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"

if let addedDate = addedDateFormatter.date(from: addedDateString) {

    // Converstion String to Date return a valid Date
    print ("addedDate", addedDate)
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd MM YYYY"
    let dateString = dateFormatter.string(from: addedDate)
    print("Date: ", dateString)

} else {

    // addedDate == nil value when conversion String to Date failed
    print ("addedDateString not valid")

}

You can also make a function. Something like this:

func transformStringDate(_ dateString: String,
                         fromDateFormat: String,
                         toDateFormat: String) -> String? {

    let initalFormatter = DateFormatter()
    initalFormatter.dateFormat = fromDateFormat

    guard let initialDate = initalFormatter.date(from: dateString) else {
        print ("Error in dateString or in fromDateFormat")
        return nil
    }

    let resultFormatter = DateFormatter()
    resultFormatter.dateFormat = toDateFormat

    return resultFormatter.string(from: initialDate)
}

print (transformStringDate("Tue, 25 May 2010 12:53:58 +0000",
                           fromDateFormat: "E, d MMM yyyy HH:mm:ss Z",
                           toDateFormat: "dd MM YYYY") ?? "Error")