2017-03-10 71 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!)") 
相关问题