【问题标题】:Confusing result of NSCalendar.dateFromComponents [duplicate]NSCalendar.dateFromComponents 的结果令人困惑 [重复]
【发布时间】:2015-07-02 13:05:22
【问题描述】:

我尝试使用此 Swift 代码获取当前日期,不包含小时和分钟:

let calendar = NSCalendar.currentCalendar()

let components = calendar.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay, fromDate: NSDate())

println(components)

let date = calendar.dateFromComponents(components)

println(date)

println 得到的结果让我有点困惑:

<NSDateComponents: 0x7fb5ad867700>
    Calendar Year: 2015
    Month: 7
    Leap month: no
    Day: 2

2015-07-01 22:00:00 +0000

components 是 2015-07-02 但结果 date 是 2015-07-01 22:00:00

我的错误在哪里?


NSDateFormatter 提到的结果很好:

var dateFormatter = NSDateFormatter()

dateFormatter.dateStyle = NSDateFormatterStyle.LongStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle

println(dateFormatter.stringFromDate(date!))

结果:

July 2, 2015 at 12:00 AM

【问题讨论】:

  • 使用 dateformatter 或不调用 dateFormComponents 将其转换为字符串。默认日期对象将在其格式中默认包含时间。
  • 我的声誉很低,无法投票给您的答案,但我用复选标记标记了它。

标签: ios swift foundation


【解决方案1】:

推进是println(date) 的工作方式。它使用NSDatedescription 方法并返回引用到GMT (UTC) 的数据。因此,您将看到基于您的时区与 GMT 的偏移量的差异。

在输出“2015-07-01 22:00:00 +0000”中,注意结尾“+0000”是时区偏移量,即 GMT,而不是您的时区。

结果是使用日期格式化程序并指定时区,对于设备的时区,您可以使用系统时区:[NSTimeZone systemTimeZone]NSTimeZone.systemTimeZone() 用于 Swift。

【讨论】:

  • 好的,我明白了。 dateist 正确,但 println(components) 显示 NSTimeZone.systemTimeZone()println(date) 使用 GTM 的结果。我试过NSDateFormatter() 并得到正确的日期。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-07
相关资源
最近更新 更多