How does one use NSDateFormatter's isLenient option?

后端 未结 1 1363
一整个雨季
一整个雨季 2021-01-21 06:44

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

相关标签:
1条回答
  • 2021-01-21 07:36

    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
    
    0 讨论(0)
提交回复
热议问题