NSDateFormatter仍在解析而不是格式不正确 [英] NSDateFormatter still parsing instead having incorrect format

查看:115
本文介绍了NSDateFormatter仍在解析而不是格式不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解析日期时遇到一些问题。我有一系列支持的格式,一旦我从API收到日期(字符串),我尝试解析它迭代格式,直到我得到一个有效的NSDate对象。

Having some problems parsing date. I have an array of supported formats and once I receive the date (string) from API, I try to parse it iterating through the formats until I get a valid NSDate object.

来自Xcode Playground的片段 -

A snippet from Xcode Playground --

let dateString = "02/06/1987" // --> want to parse into this Feb 6, not Jun 2
let dateFormatIncorrect = "dd.MM.yyyy"
let dateFormatCorrect = "MM/dd/yyyy"
let dateFormatter = NSDateFormatter()

dateFormatter.dateFormat = dateFormatIncorrect
let date = dateFormatter.dateFromString(dateString)! // "Jun 2, 1987, 12:00 AM"

dateFormatter.dateFormat = dateFormatCorrect
let date2 = dateFormatter.dateFromString(dateString)! // "Feb 6, 1987, 12:00 AM"

为什么它会解析日期,即使对于给定的字符串,格式显然不正确?无法在文档中找到有关日期格式化程序忽略分隔符的任何内容。

Why does it parse the date even though the format is clearly incorrect for a given string? Could not find anything in the docs regarding date formatter ignoring separators.

我意识到正确的解决方案是从API返回固定格式但是想知道这里发生了什么?

I realise the proper solution would be to have a fixed format returned from API but was wondering what is happening here?

谢谢。

推荐答案

似乎<$ c $当解析日期字符串时,c> NSDateFormatter 非常宽松。
不幸的是,我找不到这方面的参考,但即使有

It seems that NSDateFormatter is extremely lenient when parsing a date string. Unfortunately, I could not find a reference for this, but even with

dateFormatIncorrect = "'aaa'dd'bbb'MM'ccc'yyyy'ddd'"

日期字符串02/06/1987已成功解析。有一个 lenient 属性,
但默认情况下是 false ,并明确设置它没有区别。

the date string "02/06/1987" is successfully parsed. There is a lenient property, but that is false by default, and setting it explicitly makes no difference.

作为解决方法,您可以将解析后的日期转换回字符串,并且仅当
结果等于原始字符串,接受日期:

As a workaround, you could convert the parsed date back to a string, and only if the result is equal to the original string, the date is accepted:

extension NSDateFormatter {

    func checkedDateFromString(string : String) -> NSDate? {
        if let date = self.dateFromString(string) {
            if self.stringFromDate(date) == string {
                return date
            }
        }
        return nil
    }
}

使用此自定义扩展程序

dateFormatter.checkedDateFromString(dateString)

对于错误的日期格式返回 nil

returns nil for the incorrect date format.

通常,如果使用固定日期格式,还应将区域设置
设置为en_US_POSIX

Generally, if you work with fixed date formats, you should also set the locale to "en_US_POSIX"

dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")

(参见处理NSDateFormatter语言环境的最佳方法是什么?feechur ; )。但是,这对于这个
特定问题没有区别。

(see What is the best way to deal with the NSDateFormatter locale "feechur"?). However, this makes no difference for this particular problem.

Swift 3更新:

extension DateFormatter {

    func checkedDate(from: String) -> Date? {
        if let date = date(from: from), string(from: date) == from {
            return date
        }
        return nil
    }
}

这篇关于NSDateFormatter仍在解析而不是格式不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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