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

Output screen.

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)

Share:
81,244
Paolo Gdf
Author by

Paolo Gdf

Updated on July 02, 2020

Comments

  • Paolo Gdf
    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 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.

  • Paolo Gdf
    Paolo Gdf over 7 years
    I 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
    Fattie about 7 years
    NOTE HOWEVER you have to cache date formatters in iOS: stackoverflow.com/a/42370648/294884
  • Vineesh TP
    Vineesh TP almost 7 years
    @Andand Nimje : Have you noticed that, one day decremented after the convertion
  • Anand Nimje
    Anand Nimje almost 7 years
    Let me check @VineeshTP
  • Anand Nimje
    Anand Nimje almost 7 years
    Thank you so much @VineeshTP for your suggestion.
  • mask8
    mask8 almost 7 years
    shouldn't mm be upper case?
  • Pulkit Kumar Singh
    Pulkit Kumar Singh over 6 years
    not working ....date are coming incorrect after converting to date
  • Anand Nimje
    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
    Pulkit Kumar Singh over 6 years
    date , 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
    Anand Nimje over 6 years
    if you trying to convert String to Date then code working fine. @PulkitKumarSingh I can show you Playground screenshot. I think still you not able to understand code.
  • Pulkit Kumar Singh
    Pulkit Kumar Singh over 6 years
    Please run your code ......I am still not able to convert string to date.....date is coming incorrect...ran again!!
  • GilroyKilroy
    GilroyKilroy over 6 years
    If 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
    Mark Gerrior about 6 years
    mm is minute. MM is month. Single M or double M works. Date Formaters > Date Format Patterns
  • oscar castellon
    oscar castellon almost 6 years
    change "dd-MM-yyyy" instead "dd-mm-yyyy"
  • nitin.agam
    nitin.agam over 5 years
    Unsafe code and why you are using NS classes (NSCalendar, NSDateComponents) in Swift class?
  • Jeet Gandhi
    Jeet Gandhi over 5 years
    Thanks for pointing out. Please check it.
  • ssowri1
    ssowri1 about 5 years
    Thank you for your help!