Converting a String to a Date in Swift
10,346
Solution 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"
Solution 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")
Related videos on Youtube
Comments
-
Abhishek Thapliyal over 1 year
I have date in string with format below code want to change in
Date
but i'm gettingnil
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)")
-
vadian over 6 yearsDo you notice that
dateFormat
does not match the format ofaddedDate
at all? -
Abhishek Thapliyal over 6 yearsIf i would know that thing why i will ask here..
-
-
Flexicoder over 6 yearsIf you want to display the date in that format you'll need to set up another formatter - take a look at stackoverflow.com/a/42231620/285190
-
Sulthan over 6 yearsYou also have to set the locale to English.