How to get Date from String in swift 3?

半城伤御伤魂 提交于 2019-12-04 18:39:17

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 
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!