Swift:设置DateComponents年

时间:2017-03-10 02:13:24

标签: swift date swift3 nsdate nsdatecomponents

下面的示例代码从当前Date获取DateComponents,修改组件,并从修改后的组件创建新Date。它还显示了创建一个新的DateComponents对象,填充它,然后从中创建一个新的Date。

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对象并将其填充然后从中创建一个Date,它将按预期工作。

代码的输出如下所示:

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 个答案:

答案 0 :(得分:3)

如果您记录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!)")