2017-03-10 70 views
1

下面的示例代碼從當前日期獲取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對象初始化了一年,似乎並不適用,但這是我在文檔中看到的唯一可以解釋我觀察到的行爲的東西。

回答

1

如果您登錄nowdc您將會看到該問題。 now正在從Date創建。這填寫了所有日期組件,包括yearForWeekOfYear和幾個與工作日相關的組件。這些組件導致modDate不正確。

newDate按預期工作,因爲只設置特定組件。

如果您重置某些額外的組件,您可以正確得到modDate。具體地說,在添加:

now.yearForWeekOfYear = nil 

只是創造modDate將導致modDate預產期前。當然,最好的解決方案是創建一個新實例DateComponents,並根據需要使用以前的DateComponents的特定值:

let mod = DateComponents() 
mod.timeZone = now.timeZone 
mod.year = 2010 
mod.month = 2 
mod.day = 24 
mod.hour = now.hour 
mod.minute = 0 
mod.second = now.second 
print("\nModified Date:") 
print("\(mod.month!)/\(mod.day!)/\(mod.year!) \(mod.hour!):\(mod.minute!):\(mod.second!) \(mod.timeZone!)") 
let modDate = calendar.date(from: mod) 
print("\(modDate!)") 
相關問題