Swift - NSDate - 删除部分日期 [英] Swift - NSDate - remove part of date
问题描述
我有以下格式的日期 2015-02-22T20:58:16+0000
为了将其转换为 NSDate,我找到了以下解决方案
In order to convert it to NSDate I found following solution
var df = NSDateFormatter()
df.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZ"
var date = df.dateFromString(myDate)
df.dateFormat = "eee MMM dd yyyy"
var dateStr = df.stringFromDate(date!)
但我想从日期中删除 +0000.我试图删除 ZZZZm 但应用程序崩溃.
But I want to remove +0000 from date. I tried to remove ZZZZm but app crashes.
如何删除多余的 +0000 位数字?
How can I remove extra +0000 digits ?
推荐答案
你问:
如何删除多余的 +0000 位数字?
How can I remove extra +0000 digits?
我不确定您的意思,因为结果 dateStr
确实 删除了 +0000
.
I'm not sure what you mean, because the resulting dateStr
does have the +0000
removed.
但让我们退后一步,考虑解析 2015-02-22T20:58:16+0000
格式的日期字符串的正确方法.您应该使用 en_US_POSIX
的 locale
,如 Apple 技术问答 1480:
But let's step back and consider the right way to parse a date string in the format of 2015-02-22T20:58:16+0000
. You should use a locale
of en_US_POSIX
as described in Apple Technical Q&A 1480:
let myDate = "2015-02-22T20:58:16+0000"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
let date = dateFormatter.dateFromString(myDate)
当您想要为最终用户设置格式时,将 locale
重置回 currentLocale
:
When you then want to format that for the end user, reset the locale
back to currentLocale
:
dateFormatter.locale = NSLocale.currentLocale()
dateFormatter.dateFormat = "eee MMM dd yyyy"
let dateStr = dateFormatter.stringFromDate(date!)
dateStr
然后变成:
2015 年 2 月 22 日星期日
Sun Feb 22 2015
或者,也许更好,为了更好的本地化行为,使用 dateFormatFromTemplate
:
Or, perhaps better, for better localization behavior, use dateFormatFromTemplate
:
let locale = NSLocale.currentLocale()
dateFormatter.locale = locale
dateFormatter.dateFormat = NSDateFormatter.dateFormatFromTemplate("eeeMMMdyyyy", options: 0, locale: locale)
let dateStr = dateFormatter.stringFromDate(date!)
在美国,它会显示如上,但在英国,它会显示为:
In the US, it will appear like above, but in England it will appear as:
2015 年 2 月 22 日,星期日
Sun, 22 Feb 2015
或者使用标准的 dateStyle
值之一,如果它适合您的话.但我通常建议不要使用硬编码的 dateFormat
,而是使用尊重最终用户本地化设置的格式.
Or use one of the standard dateStyle
values if that works for you. But I'd generally advise against using a hard-coded dateFormat
, but rather use a format that honors the end-user's localization settings.
这篇关于Swift - NSDate - 删除部分日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!