How to get Date from String in swift 3?

I have save the timestamp in data base like:

"NSDate()" // which save Date like this: 2017-03-10 22:53:30 +0000

Now i need to get Date from this string, I have tried every format but it’s keep returning nil.

  • Produce ultrasonic sound on an iOS device
  • Trouble setting label text in iOS
  • iOS Present modal view controller on startup without flash
  • UIButton w/ gradient, rounded corners, border, and drop shadow
  • ImportError: No module named zope.interface
  • Swift: Navigate to new ViewController using button
  •     let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd hh:mm:ss ZZZ"
        dateFormatter.locale = Locale(identifier: "en_US")
        print(dateFormatter.date(from: "2017-03-10 22:53:30 +0000") ?? "No Value") // always return No Value
    

    here i have tried so many formats e.g:
    yyyy-MM-dd hh:mm:ss +zzzz
    yyyy-MM-dd hh:mm:ss xx

    Have seen many answers but no answer is working on this format of date “2017-03-10 22:53:30 +0000”

    3 Solutions Collect From Internet About “How to get Date from String in swift 3?”

    Military time (24-value hours) uses the capital ‘H’. Try this for your formatting String:

    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
    

    hh is a 12-hour hours. You need HH if you have a 24-hour hour padding. Check http://nsdateformatter.com for more details about NSDateFormatter formats.

    I am using this code while converting String to Date .
    (Swift 3)

    extension String
    {
         func  toDate( dateFormat format  : String) -> Date
        {
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = format
            if let date = dateFormatter.date(from: self)
            {
                return date
            }
            print("Invalid arguments ! Returning Current Date . ")
            return Date()
        }
    }
    

    and just call like . .

     print ( "2016-06-20T13:01:46.457+02:00".toDate(dateFormat: "yyyy-MM-dd'T'HH:mm:ss.SSSZ") )
    //Capital HH for 24-Hour Time