首页 文章

获得两个NSDates之间的分钟和小时数?

提问于
浏览
0

根据this question,让's say I need to get the hours and minutes between two NSDates. For example, one date is 3 hours and 42 minutes after the other. How would I get both hours and minutes of the time elapsed? I' ve尝试了类似的东西,但它没有 both 吨获得 both 小时和分钟 .

我也尝试过使用NSCalendar,但这也没有用 . 相反,它只给了我小时数和秒数,而不是一次测量 .

有任何想法吗?

3 回答

  • 3

    Mac OS X 10.10 Yosemite引入智能NSDateComponentsFormatter来显示组件中的时间间隔,如 18h 56m 4s

    此片段的结果是从午夜到现在的格式化时间间隔 .

    let calendar = NSCalendar.currentCalendar()
    let midnight = calendar.startOfDayForDate(NSDate())
    let timeinterval = NSDate().timeIntervalSinceDate(midnight)
    
    let formatter = NSDateComponentsFormatter()
    formatter.unitsStyle = .Abbreviated
    formatter.stringFromTimeInterval(timeinterval)
    
  • 5

    间隔以秒为单位 - 这可以为您提供小时和分钟 . 只是数学一点点 .

    let hours = totalTime / 3600
    let minutes = (totalTime % 3600) / 60
    
  • 5

    无需日历即可轻松获得平面数学 .

    let now = NSDate()
    let latest = NSDate(timeInterval: 3*3600+42*60, sinceDate: now)
    
    let difference = latest.timeIntervalSinceDate(now)
    
    let hours = Int(difference) / 3600
    let minutes = (Int(difference) / 60) % 60
    

    这将为您提供小时和分钟的间隔 . 注意:不要忘记转换为整数,因为NSTimeInterval是浮点类型 .

相关问题