<分区>
我正在测试一个具有 UITextField 的应用程序,用户可以在其中输入日期,因此我获取输入的字符串并使用 DateFormatter 生成 Date 对象。
当我尝试转换返回 nil 值的字符串“10/15/2017”时,问题首先出现。所以我创建了一个代码来生成从“01/01/2000”到“12/31/2020”的字符串,我意识到这个问题在每年 10 月或 11 月左右的所有年份都会发生。 我创建了一个代码来打印所有返回 nil 值的日期:
import UIKit
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.locale = Locale(identifier: "en_US")
for day in 1...30 { // Generate the days
for month in 1...12 { // Generate the months
for year in 2000...2020 {
if month == 2, day > 28 { // Check if month is february
continue
}
str = "\(String(format: "%02d", month))/\(String(format: "%02d", day))/\(String(format: "%02d", year))"
let date = dateFormatter.date(from: str)
if date == nil {
print("\(str)")
}
}
}
}
我还尝试更改 dateFormat
,甚至更改 locale
属性,但某些条目也为 nil。
dateFormatter.dateFormat = "MM/dd/yyyy"
这段代码打印出以下内容:
11/02/2004
11/03/2002
11/05/2006
10/08/2000
10/14/2001
10/14/2007
10/15/2017
10/16/2005
10/16/2011
10/16/2016
10/17/2010
10/18/2009
10/18/2015
10/18/2020
10/19/2003
10/19/2008
10/19/2014
10/20/2013
10/20/2019
10/21/2012
10/21/2018
我正在使用 Xcode 8.3.3 和 Swift 3。这是 Swift/Xcode 的错误还是我做错了什么?