Convert string to date in Swift

I have a date in a line with a format below the code that needs to be changed in Date but I get 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

-one
date cocoa-touch cocoa swift nsdateformatter
Jul 30 '17 at 10:55
source share
2 answers

The date format should be for the string you are trying to convert, not the format you want to return

So

 formatter.dateFormat = "dd MM YYYY" 

it should be

 formatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z" 
+2
Jul 30 '17 at 11:00
source share

Do you need to convert string String (addDateString) to Date? (addDate), then you can convert it to String (dateString) using the desired format. Note: addDate is zero when converting from String to Date.

 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 that:

 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") 
0
Jul 30 '17 at 13:38 on
source share



All Articles