我正在测试一个具有用户输入日期的UITextField的应用程序,因此我使用输入的字符串并使用DateFormatter生成Date对象。DateFormatter中的Swift语言错误?
问题首次发生时,我试图转换字符串“10/15/2017”,返回一个零值。因此,我创建了一个代码来生成从“01/01/2000”到“12/31/2020”的字符串,并且我意识到问题发生在每年10月或11月左右的所有年份。 我创建了一个代码,打印返回一个零值的所有日期:
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
性质,我也越来越零对一些条目。
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和斯威夫特三是与斯威夫特/ Xcode的bug或我在做什么错误?
我不能复制。 - 但是你应该使用固定的'dateFormatter.dateFormat'(在你的情况下:“MM/dd/yyyy”)*解析*日期。 –
@MartinR我尝试使用'dateFormatter.dateFormat'与“MM/dd/yyyy”以及“dd/MM/yyyy”,但我得到了相同的结果。 –
你的时区是什么? –