Convert string to DATE type in swift 3
81,244
Solution 1
You can convert String Date into Date/NSDate like below code: -
Swift 3.2 & Swift 4.2
String to Date
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy" //Your date format
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00") //Current time zone
//according to date format your date string
guard let date = dateFormatter.date(from: "01-01-2017") else {
fatalError()
}
print(date) //Convert String to Date
Date to String
dateFormatter.dateFormat = "MMM d, yyyy" //Your New Date format as per requirement change it own
let newDate = dateFormatter.string(from: date) //pass Date here
print(newDate) //New formatted Date string
Output: -
2017-01-11 00:07:00 +0000
Jan 11, 2017
Solution 2
Swift 4 ISO
let dateFormatter = DateFormatter()
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone.autoupdatingCurrent
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
Solution 3
func getDateFromString(dateStr: String) -> (date: Date?,conversion: Bool)
{
let calendar = Calendar(identifier: Calendar.Identifier.gregorian)
let dateComponentArray = dateStr.components(separatedBy: "/")
if dateComponentArray.count == 3 {
var components = DateComponents()
components.year = Int(dateComponentArray[2])
components.month = Int(dateComponentArray[1])
components.day = Int(dateComponentArray[0])
components.timeZone = TimeZone(abbreviation: "GMT+0:00")
guard let date = calendar.date(from: components) else {
return (nil , false)
}
return (date,true)
} else {
return (nil,false)
}
}
//Input: "23/02/2017"
//Output: (2017-02-23 18:30:00 +0000, true)
Author by
Paolo Gdf
Updated on July 02, 2020Comments
-
Paolo Gdf almost 4 years
I have this structure:
struct message { var id: String = "0" var text: String = "" var date: Date! var status: String = "" }
I have to load this structure from dbase, that it export in
String
format alsodate
. So I write this code to convertString
toDate
type:let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" dateFormatter.timeZone = NSTimeZone(abbreviation: "UTC") as TimeZone! let dataDate = dateFormatter.date(from: elemMessage["date"] as! String)!
And I load it in structure:
message(id: elemMessage["id"] as! String, text: elemMessage["text"] as! String, date: dataDate as! Date, status: elemMessage["status"] as! String)
But I have this warning: "Cast from
Date
to unrelated typeDate
always fails"So if I run app it will fails.
How Can I fix this, the
date
var in structure have to beDate
type.Thank you.
-
Paolo Gdf over 7 yearsI have used your code but i have error: ` Cannot convert value of type 'Date?' to expected argument type 'Date!' ` when load it in structure message.
-
Fattie about 7 yearsNOTE HOWEVER you have to cache date formatters in iOS: stackoverflow.com/a/42370648/294884
-
Vineesh TP almost 7 years@Andand Nimje : Have you noticed that, one day decremented after the convertion
-
Anand Nimje almost 7 yearsLet me check @VineeshTP
-
Anand Nimje almost 7 yearsThank you so much @VineeshTP for your suggestion.
-
mask8 almost 7 yearsshouldn't
mm
be upper case? -
Pulkit Kumar Singh over 6 yearsnot working ....date are coming incorrect after converting to date
-
Anand Nimje over 6 years@PulkitKumarSingh what problem are you facing can you tell me in details so i can help you. I think are you doing something wrong.
-
Pulkit Kumar Singh over 6 yearsdate , month , year was coming incorrect ...time was right ....my date was in format "20-02-2018 06:20" ...i copied your code and then ran it. It was giving current date.
-
Anand Nimje over 6 yearsif you trying to convert
String
toDate
then code working fine. @PulkitKumarSingh I can show you Playground screenshot. I think still you not able to understand code. -
Pulkit Kumar Singh over 6 yearsPlease run your code ......I am still not able to convert string to date.....date is coming incorrect...ran again!!
-
GilroyKilroy over 6 yearsIf you look closely at the output screen you see you converted July 11, 2017 but actually got January 11, 2017. You want the date format string to be "dd-MM-yyyy"
-
Mark Gerrior about 6 yearsmm is minute. MM is month. Single M or double M works. Date Formaters > Date Format Patterns
-
oscar castellon almost 6 yearschange "dd-MM-yyyy" instead "dd-mm-yyyy"
-
nitin.agam over 5 yearsUnsafe code and why you are using NS classes (NSCalendar, NSDateComponents) in Swift class?
-
Jeet Gandhi over 5 yearsThanks for pointing out. Please check it.
-
ssowri1 about 5 yearsThank you for your help!