【问题标题】:How to get the correct time Using NSDate with components in swift如何在 swift 中将 NSDate 与组件一起使用以获取正确的时间
【发布时间】:2016-06-10 15:11:23
【问题描述】:

当我得到像秒这样的组件时:

NSCalendar.currentCalendar().components(.Second, fromDate: savedDate, toDate: todayDate, options: []).second

我得到了自该日期以来的秒数。 但是我正在尝试获取所有组件,例如天数和小时数,它为我提供了每个组件的总数。

如果我知道小时数,让我们说 36 小时,那么天数将显示为一天。

1我希望它显示 1 天 12 小时。

2.如何使用这些组件启动计数器或计时器?

【问题讨论】:

    标签: ios swift nsdate


    【解决方案1】:

    您必须在components 参数中指定要考虑的所有单位。

    let components = NSCalendar.currentCalendar().components([.Second, .Minute, .Hour, .Day], fromDate: savedDate, toDate: todayDate, options: [])
    print(components)
    

    或者使用NSDateComponentsFormatter,它可以创建一个(本地化的)字符串。指定要显示的单位和样式。

    let formatter = NSDateComponentsFormatter()
    formatter.allowedUnits = [.Day, .Hour, .Minute, .Second ]
    formatter.unitsStyle = .Full
    let dateString = formatter.stringFromDate(savedDate, toDate: todayDate)!
    print(dateString)
    

    关于你的第二个问题,让计数器以秒为单位计数,并相应地格式化秒以供人类阅读。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-09
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 2016-11-18
      • 2017-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多