J. *_*coe 3 foundation nsdateformatter swift swift3
我似乎无法在 StackOverflow 或网络上的其他地方找到有关此标志的任何信息。苹果自己的文档只说:
如果格式化程序设置为宽松,则在解析字符串时,它会使用启发式方法来猜测预期的日期。与任何猜测一样,它可能会得到错误的结果日期(即,不是预期的日期)。
也许我误解了它应该如何工作,但我根本无法让它工作。我的猜测是这样的(解析日期相对容易):
> import Foundation
> let df = DateFormatter()
> df.isLenient = true
> df.date(from: "12:00 1/1/2001")
$R0: Date? = nil
Run Code Online (Sandbox Code Playgroud)
无论我尝试什么,我都没有。
我还看到有一个doesRelativeDateFormatting标志,声称支持诸如“今天”和“明天”之类的短语,但这似乎也没有任何作用:
> df.doesRelativeDateFormatting = true
> df.date(from: "today")
$R1: Date? = nil
Run Code Online (Sandbox Code Playgroud)
有任何想法吗?
这是一个示例,其中 lenient 选项有所不同:
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)
Run Code Online (Sandbox Code Playgroud)
2015 年不是闰年,所以没有 2 月 29 日。用
isLenient = true,日期被解释为 3 月 1 日。用isLenient = false它被拒绝:
let df = DateFormatter()
df.timeZone = TimeZone(secondsFromGMT: 0)
df.isLenient = false
df.dateFormat = "yyyy-MM-dd"
print(df.date(from: "2015-02-29")) // nil
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
709 次 |
| 最近记录: |