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 (eg 2015-06-11T00:00:00.000Z
) and send it to the server.
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"
}
}
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.