如何将字符添加到dateFormatter [英] How to add characters into dateFormatter

查看:55
本文介绍了如何将字符添加到dateFormatter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了答案,但这对我不起作用。

I followed this answer, but it doesn't work for me.

我想将时间格式化为:


2017-09-11 T 11:45:00-04:00

"2017-09-11T11:45:00-04:00"

我在做:

let xFormatter = DateFormatter()
xFormatter.dateFormat = "yyyy-MM-ddTHH:mm:ss-04:00"
print(xFormatter.string(from: date))

我需要在日期和日期之间输入 T 时间。但是,如果添加了该格式,我的格式将变为:

I need a T between the date and time. however if I add that, my format turns into something like:


2017-09-11

2017-09-11

(最后的-4:00是一个时间偏移,我用硬编码...)

(The -4:00 at the end is a timeoffset which I hardcode...)

推荐答案

添加单引号

xFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss-04:00"

摘自文档:


...如果要表示文字文本,则需要将ASCII字母括在单引号中。

... This includes the need to enclose ASCII letters in single quotes if they are intended to represent literal text.

来源: Unicode.org :日期格式模式

编辑:

请注意,

要考虑时区,必须将设置为时区,只是对字符串的修改。 timeZone

xFormatter.timeZone = TimeZone(secondsFromGMT: -14400)

在iOS 10.0+和macOS 10.12+中,有一种更方便的方法来创建ISO8601字符串

In iOS 10.0+ and macOS 10.12+ there is a more convenient way to create an ISO8601 string

let isoFormatter = ISO8601DateFormatter()
isoFormatter.timeZone = TimeZone(secondsFromGMT: -14400)
isoFormatter.formatOptions = .withInternetDateTime
print(isoFormatter.string(from: Date()))

这篇关于如何将字符添加到dateFormatter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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