Convert String To Date In Swift


Answer :


  • Convert the ISO8601 string to date



    let isoDate = "2016-04-14T10:44:00+0000"

    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let date = dateFormatter.date(from:isoDate)!

  • Get the date components for year, month, day and hour from the date



    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)

  • Finally create a new Date object and strip minutes and seconds



    let finalDate = calendar.date(from:components)






Consider also the convenience formatter ISO8601DateFormatter introduced in iOS 10 / macOS 12:



let isoDate = "2016-04-14T10:44:00+0000"

let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!


Try the following date Format.



let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let date = dateFormatter. dateFromString (strDate)


Hope it helps..



Swift 4.1 :



let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"
let date = dateFormatter.date(from: strDate)


In Swift 4.1 you can do:



func getDate() -> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
dateFormatter.timeZone = TimeZone.current
dateFormatter.locale = Locale.current
return dateFormatter.date(from: "2015-04-01T11:42:00") // replace Date String
}


Comments

Popular posts from this blog

Converting A String To Int In Groovy

"Cannot Create Cache Directory /home//.composer/cache/repo/https---packagist.org/, Or Directory Is Not Writable. Proceeding Without Cache"

Android How Can I Convert A String To A Editable