How to get Date from String in swift 3?

2020-07-30 04:22发布

问题:

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.

    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"

回答1:

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

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


回答2:

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.



回答3:

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