我已经测试了几个格式化程序,但我得到的结果是2秒,很奇怪。 我已经阅读了一些有关堆栈溢出的帖子,但之前没有看到过类似的内容。
func testDates() {
let formatter = NSDateFormatter()
formatter.locale = NSLocale.systemLocale()
formatter.dateFormat = "yyyy-M-d"
formatter.timeZone = NSTimeZone.systemTimeZone()
let formatter2 = NSDateFormatter()
formatter2.locale = NSLocale(localeIdentifier: "en_US_POSIX")
formatter2.dateFormat = "yyyy-MM-dd"
formatter2.timeZone = NSTimeZone.systemTimeZone()
let tests = ["923-05-17","1700-05-01", "1701-9-9", "1702-9-01", "1703-09-5", "1991-01-05"]
let dates = tests.map({$0.toDate(formatter)})
let dates2 = tests.map({$0.toDate(formatter2)})
println(dates)
}
extension String {
func toDate(formatter: NSDateFormatter) -> NSDate? {
return formatter.dateFromString(self)
}
}
结果是:
Printing description of dates:
([NSDate?]) dates = 6 values {
[0] = 0923-05-16 23:52:58 PST
[1] = 1700-04-30 23:52:58 PST
[2] = 1701-09-08 23:52:58 PST
[3] = 1702-08-31 23:52:58 PST
[4] = 1703-09-04 23:52:58 PST
[5] = 1991-01-05 00:00:00 PST
}
Printing description of dates2:
([NSDate?]) dates2 = 6 values {
[0] = 0923-05-16 23:52:58 PST
[1] = 1700-04-30 23:52:58 PST
[2] = 1701-09-08 23:52:58 PST
[3] = 1702-08-31 23:52:58 PST
[4] = 1703-09-04 23:52:58 PST
[5] = 1991-01-05 00:00:00 PST
}
(lldb)
答案 0 :(得分:0)
似乎这是解析20世纪之前的日期的问题:)
var centuries = [String]()
for x in 0...22 {
centuries.append("\(x*100)-01-01")
}
let centuriesDates = centuries.map({$0.toDate(formatter)})
Printing description of centuries:
([String]) centuries = 23 values {
[0] = "0-01-01"
[1] = "100-01-01"
[2] = "200-01-01"
[3] = "300-01-01"
[4] = "400-01-01"
[5] = "500-01-01"
[6] = "600-01-01"
[7] = "700-01-01"
[8] = "800-01-01"
[9] = "900-01-01"
[10] = "1000-01-01"
[11] = "1100-01-01"
[12] = "1200-01-01"
[13] = "1300-01-01"
[14] = "1400-01-01"
[15] = "1500-01-01"
[16] = "1600-01-01"
[17] = "1700-01-01"
[18] = "1800-01-01"
[19] = "1900-01-01"
[20] = "2000-01-01"
[21] = "2100-01-01"
[22] = "2200-01-01"
}
Printing description of centuriesDates:
([NSDate?]) centuriesDates = 23 values {
[0] = nil
[1] = 0099-12-31 23:52:58 PST
[2] = 0199-12-31 23:52:58 PST
[3] = 0299-12-31 23:52:58 PST
[4] = 0399-12-31 23:52:58 PST
[5] = 0499-12-31 23:52:58 PST
[6] = 0599-12-31 23:52:58 PST
[7] = 0699-12-31 23:52:58 PST
[8] = 0799-12-31 23:52:58 PST
[9] = 0899-12-31 23:52:58 PST
[10] = 0999-12-31 23:52:58 PST
[11] = 1099-12-31 23:52:58 PST
[12] = 1199-12-31 23:52:58 PST
[13] = 1299-12-31 23:52:58 PST
[14] = 1399-12-31 23:52:58 PST
[15] = 1499-12-31 23:52:58 PST
[16] = 1599-12-31 23:52:58 PST
[17] = 1699-12-31 23:52:58 PST
[18] = 1799-12-31 23:52:58 PST
[19] = 1900-01-01 00:00:00 PST <<<< Finally started working
[20] = 2000-01-01 00:00:00 PST
[21] = 2100-01-01 00:00:00 PST
[22] = 2200-01-01 00:00:00 PST
}
(lldb)