nsdate – Convert string to date in Swift

nsdate – Convert string to date in Swift

  • 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-ddTHH: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-ddTHH:mm:ssZZZ
let date = dateFormatter. dateFromString (strDate)

Hope it helps..

Swift 4.1 :

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = yyyy-MM-ddTHH:mm:ssZZZ
let date = dateFormatter.date(from: strDate)

nsdate – Convert string to date in Swift

In Swift 4.1 you can do:

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

Leave a Reply

Your email address will not be published. Required fields are marked *