Combining time and date in ISO8601 format string using Swift

2.7k Views Asked by At

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.

2

There are 2 best solutions below

0
On BEST ANSWER

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"
    }
}
0
On

Strings are textual representations of dates and often include an explicit or implicit timezone. NSDate represents a date in UTC.

If you want to add an hour, you convert the string to NSDate, add an hour, convert it to a string. The conversion will take care for example of daylight savings time, where one hour after 2:30am might be 4:30am. Or 2:30am.