【问题标题】:How to fetch day, month and hour from NSDate in Swift如何在 Swift 中从 NSDate 获取日、月和小时
【发布时间】:2016-08-05 10:05:55
【问题描述】:

我有一个名为 reservationDate 的 NSDate 对象,我想从日期中获取 日、月和小时。但是,我得到了错误的值。我怎样才能得到这些值?

reservationDate 对象的值 预订日期NSDate2016-08-05 21:00:00 UTC 因此,我希望每天收到 5 个,每小时收到 21 个,但是我每天收到 6 个,一个小时收到 0 个。我应该期待别的吗?

let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year]
let components = NSCalendar.currentCalendar().components(unitFlags, fromDate: reservationDate)
let day = components.day
let hour = components.hour

【问题讨论】:

  • 它给出 UTC 时间格式
  • 你想要什么结果?格林威治 (GMT/UTC) 挂钟上显示的小时数还是您所在位置的小时数?

标签: swift nsdate nsdatecomponents


【解决方案1】:

您尚未设置时区。请将其指定为“UTC”。

NSCalendar.currentCalendar().timeZone = NSTimeZone(name: "UTC")!

【讨论】:

    【解决方案2】:

    尝试使用Calendar 对象和UTC 设置时区

    let unitFlags: NSCalendarUnit = [.Hour, .Day, .Month, .Year]
    let calendar = NSCalendar.currentCalendar()
    calendar.timeZone = NSTimeZone(name: "UTC")!
    let components = calendar.components(unitFlags, fromDate: NSDate())
    let day = components.day
    let hour = components.hour
    

    【讨论】:

      【解决方案3】:
      let currentDate = NSDate()
      let dateFormatter = NSDateFormatter()
      dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
      var convertedDate = dateFormatter.stringFromDate(currentDate)
      dateFormatter.dateFormat = "EEEE, MMMM dd, yyyy, HH:mm"
      convertedDate = dateFormatter.stringFromDate(currentDate)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-11
        • 1970-01-01
        • 2023-03-16
        • 2011-08-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多