[英]iOS NSDateFormatter dateFromString returns nil only in one instance
[英]iOS - NSDateFormatter dateFromString returns nil only in one case
我正在測試日期格式的一些值( "dd-MM-yyyy"
),有一種特殊情況我無法解釋:
var datef = NSDateFormatter()
datef.dateFormat = "dd-MM-yyyy";
var date_a = "02-01-1990"
var date_b = "01-01-1990"
var date_f_a = datef.dateFromString(date_a);
var date_f_b = datef.dateFromString(date_b);
data_f_a
返回1990年1月2日上午12:00,但date_f_b
返回nil。 除1990年1月1日外,任何其他日期都將返回預期值。
如果我添加datef.lenient = true
date_f_b不再為nil,但我不需要這樣做。 為什么它是無效的日期?
編輯1:如果我使用DateFormatter()
也會發生相同的情況:
編輯2: Xcode版本:8.1
經過一番評論后,可以確定問題中的代碼正在使用es_PE
的語言環境運行。 這是秘魯的國家。 有問題的日期是1990年1月1日。默認情況下, NSDateFormatter
使用本地時區,當解析沒有時間的日期字符串時,將假定為午夜。
在秘魯,1990年的日光節約時間是從1990年1月1日午夜開始。這意味着時鍾從1989年12月31日晚上11:59:59一直到1990年1月1日上午1:00:00。 1990年1月1日無午夜。
這就是為什么該用戶嘗試轉換字符串01-01-1990
失敗的原因。 在秘魯,這個日期沒有午夜(可能還有其他幾個同時開始夏令時的語言環境,如果有的話)。 大多數測試此代碼的人會認為它工作正常,因為大多數測試此代碼的人都不住在秘魯。
我找到了一個有用的網站,其中包含有用的信息。 有關秘魯和夏令時的詳細信息,請參見http://www.timeanddate.com/time/change/peru/lima?year=1990 。 請注意,在1989年和1991年,秘魯沒有使用夏時制。
對於xCode 7.3,您需要使用NSDateComponents
var datef = NSDateFormatter()
datef.dateFormat = "dd-MM-yyyy";
var dtCompo = NSDateComponents()
dtCompo.day = 2
dtCompo.month = 1
dtCompo.year = 1990
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
var date_f_a = cal.dateFromComponents(dtCompo)
dtCompo = NSDateComponents()
dtCompo.day = 1
dtCompo.month = 1
dtCompo.year = 1990
var date_f_b = cal.dateFromComponents(dtCompo)
var date_f_a_string = datef.stringFromDate(date_f_a!)
var date_f_b_string = datef.stringFromDate(date_f_b!)
print(date_f_a_string)
print(date_f_b_string)
var datef = DateFormatter()
datef.dateFormat = "dd-MM-yyyy";
var dtCompo = DateComponents()
dtCompo.day = 2
dtCompo.month = 1
dtCompo.year = 1990
let cal = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
var date_f_a = cal.date(from: dtCompo)
dtCompo = DateComponents()
dtCompo.day = 1
dtCompo.month = 1
dtCompo.year = 1990
var date_f_b = cal.date(from: dtCompo)
var date_f_a_string = datef.string(from: date_f_a!)
var date_f_b_string = datef.string(from: date_f_b!)
print(date_f_a_string)
print(date_f_b_string)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.