Search code examples
swiftdatecocoacocoa-touchnsdateformatter

Converting a String to a Date in Swift


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)")

enter image description here


Solution

  • 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"