【问题标题】:Swift: unexpected behavior when setting DateComponents yearSwift:设置 DateComponents 年份时出现意外行为
【发布时间】:2017-07-31 05:48:39
【问题描述】:

下面的示例代码从当前 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 对象是用一年初始化的,这似乎并不适用,但这是我在文档中看到的唯一可以解释我观察到的行为的东西。

【问题讨论】:

    标签: swift date swift3 nsdate nsdatecomponents


    【解决方案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!)")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-14
      • 2015-05-03
      相关资源
      最近更新 更多