使用Swift将时间和日期以ISO8601格式字符串组合 [英] Combining time and date in ISO8601 format string using Swift

查看:121
本文介绍了使用Swift将时间和日期以ISO8601格式字符串组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个表示日期选择器中日期和时间的texfields,但是当我解析字符串时,仅显示日期。我想将日期和时间组合成ISO8601格式的字符串(例如 2015-06-11T00:00:00.000Z )并将其发送到服务器。

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.

推荐答案

您可以使用NSCalendar方法dateBySettingHour进行操作,如下所示:

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

这篇关于使用Swift将时间和日期以ISO8601格式字符串组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆