Swift - NSDate - remove part of date

﹥>﹥吖頭↗ 提交于 2019-12-23 19:13:01

问题


I have a date in following format 2015-02-22T20:58:16+0000

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!)

But I want to remove +0000 from date. I tried to remove ZZZZm but app crashes.

How can I remove extra +0000 digits ?


回答1:


You ask:

How can I remove extra +0000 digits?

I'm not sure what you mean, because the resulting dateStr does have the +0000 removed.

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)

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!)

The dateStr then becomes:

Sun Feb 22 2015

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:

Sun, 22 Feb 2015

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.




回答2:


I wouldn't recommend removing time zone when you're parsing results. But if all you want to do is remove the string, you can do it like this:

let date = "2015-02-22T20:58:16+0000"
let display = date.substringToIndex(date.characters.indexOf("+")!)

This will give you the result of 2015-02-22T20:58:16



来源:https://stackoverflow.com/questions/35950784/swift-nsdate-remove-part-of-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!