如何使用NSDateFormatter的isLenient选项? [英] How does one use NSDateFormatter's isLenient option?

查看:158
本文介绍了如何使用NSDateFormatter的isLenient选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎在StackOverflow或网络上的其他位置都找不到此标志的任何信息.苹果自己的文档只说:

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.

我还看到有一个doesRelativeDateFormatting标志,该标志声称支持诸如"today"和"tomorrow"之类的短语,但似乎也无能为力:

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

有什么想法吗?

推荐答案

以下是lenient选项有所作为的示例:

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年不是a年,因此没有2月29日. isLenient = true,日期解释为3月1日. 使用isLenient = false会被拒绝:

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

这篇关于如何使用NSDateFormatter的isLenient选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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