Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to DATE type in swift 3 [duplicate]

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 also date. So I write this code to convert String to Date 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 type Date always fails"

So if I run app it will fails.

How Can I fix this, the date var in structure have to be Date type.

Thank you.

like image 436
Paolo Gdf Avatar asked Jan 03 '17 03:01

Paolo Gdf


2 Answers

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

Output screen.

like image 79
Anand Nimje Avatar answered Oct 16 '22 20:10

Anand Nimje


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"
like image 17
Rabie Avatar answered Oct 16 '22 21:10

Rabie