Search code examples
iosswiftdatensdatensdateformatter

Combining time and date in ISO8601 format string using Swift


I have two texfields representing date and time from the date picker, but when I parse the string only the date is displayed. I would like to combine date and time into a string in ISO8601 format (e.g. 2015-06-11T00:00:00.000Z) and send it to the server.


Solution

  • You can do it using NSCalendar method dateBySettingHour as follow:

    Xcode 8.2.1 • Swift 3.0.2

    let df = DateFormatter()
    df.calendar = Calendar(identifier: .iso8601)
    df.locale = Locale(identifier: "en_US_POSIX")
    df.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z"
    if let date = df.date(from:"2015-06-11T00:00:00.000Z") {
        let hour = 4
        if let dateWithTime = Calendar.current.date(bySettingHour: hour, minute: 0, second: 0, of: date) {
            let resultString = df.string(from: dateWithTime)
            print(resultString) // "2015-06-11T04:00:00.000Z"
        }
    }