下面的示例代碼從當前日期獲取DateComponents,修改組件,並從修改後的組件創建新日期。它還顯示創建一個新的DateComponents對象,填充它,然後創建一個新的Date。Swift:設置DateComponents時出現的意外行爲
import Foundation
let utcHourOffset = -7.0
let tz = TimeZone(secondsFromGMT: Int(utcHourOffset*60.0*60.0))!
let calendar = Calendar(identifier: .gregorian)
var now = calendar.dateComponents(in: tz, from: Date())
// Get and display current date
print("\nCurrent Date:")
print("\(now.month!)/\(now.day!)/\(now.year!) \(now.hour!):\(now.minute!):\(now.second!) \(now.timeZone!)")
let curDate = calendar.date(from: now)
print("\(curDate!)")
// Modify and display current date
now.year = 2010
now.month = 2
now.day = 24
now.minute = 0
print("\nModified Date:")
print("\(now.month!)/\(now.day!)/\(now.year!) \(now.hour!):\(now.minute!):\(now.second!) \(now.timeZone!)")
let modDate = calendar.date(from: now)
print("\(modDate!)")
// Create completely new date
var dc = DateComponents()
dc.year = 2014
dc.month = 12
dc.day = 25
dc.hour = 10
dc.minute = 12
dc.second = 34
print("\nNew Date:")
print("\(dc.month!)/\(dc.day!)/\(dc.year!) \(dc.hour!):\(dc.minute!):\(dc.second!) \(now.timeZone!)")
let newDate = calendar.date(from: dc)
print("\(newDate!)")
在我修改組件的情況下,設置不同的年,月,日等,然後使用組件獲得一個約會,我得到了意想不到的結果,新的日期已全部修改的組件除了年份保持不變之外。
在我創建一個DateComponents對象並填寫它的情況下,然後從它創建一個日期,它按預期工作。
代碼的輸出如下所示:
Current Date:
3/9/2017 19:5:30 GMT-0700 (fixed)
2017-03-10 02:05:30 +0000
Modified Date:
2/24/2010 19:0:30 GMT-0700 (fixed)
2017-02-25 02:00:30 +0000
New Date:
12/25/2014 10:12:34 GMT-0700 (fixed)
2014-12-25 17:12:34 +0000
我期望的修正的日期爲2010-02-25 02:00:30 +0000
而非2017-02-25 02:00:30 +0000
。爲什麼不是?爲什麼它在第二種情況下工作?
DateComponents的docs表示:「NSDateComponents的一個實例不負責回答關於超出初始化信息的日期的問題......」。由於DateComponents對象初始化了一年,似乎並不適用,但這是我在文檔中看到的唯一可以解釋我觀察到的行爲的東西。