How does one use NSDateFormatter's isLenient o

2019-02-28 06:58发布

问题:

I can't seem to find any info on this flag, on StackOverflow or elsewhere on the web. Apple's own documentation only says:

If a formatter is set to be lenient, when parsing a string it uses heuristics to guess at the date which is intended. As with any guessing, it may get the result date wrong (that is, a date other than that which was intended).

Maybe I'm misunderstanding how this is supposed to work, but I can't get it to work at all. My guess was something like this (with a relatively easy date to parse):

> import Foundation
> let df = DateFormatter()
> df.isLenient = true
> df.date(from: "12:00 1/1/2001")
$R0: Date? = nil

No matter what I try, I get nil.

I also see there's a doesRelativeDateFormatting flag, which claims to support phrases such as “today” and “tomorrow”", but that doesn't seem to do anything, either:

> df.doesRelativeDateFormatting = true
> df.date(from: "today")
$R1: Date? = nil

Any ideas?

回答1:

Here is an example where the lenient option makes a difference:

let df = DateFormatter()
df.timeZone = TimeZone(secondsFromGMT: 0)
df.isLenient = true
df.dateFormat = "yyyy-MM-dd"
print(df.date(from: "2015-02-29")) // Optional(2015-03-01 00:00:00 +0000)

2015 is not a leap year, so there is no February 29. With isLenient = true, the date is interpreted as March 1. With isLenient = false it is rejected:

let df = DateFormatter()
df.timeZone = TimeZone(secondsFromGMT: 0)
df.isLenient = false
df.dateFormat = "yyyy-MM-dd"
print(df.date(from: "2015-02-29")) // nil