如何根据用户未来选择的时间获取总小时数

时间:2016-06-29 00:34:36

标签: ios swift

可以查找用户选择未来时间的总小时数,例如,如果当前时间是12:00 PM并且用户选择在接下来的2小时2:00 PM完成任务作为目标时间,我怎么能代表这样的2个小时"是时候完成下一个任务2小时"

这是我到目前为止所做的:

    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
    let date = formatter.dateFromString(time)!
    let calendar = NSCalendar.currentCalendar()
    let component = calendar.components([.Hour, .Minute], fromDate: date)
    print("Complete next task \(component.hour)HR")

打印出来的是:

Complete next task 20HR 

1 个答案:

答案 0 :(得分:1)

使用NSDateComponentsFormatter

let calendar = NSCalendar.currentCalendar()
let startTime = calendar.dateWithEra(1, year: 2016, month: 6, day: 28, hour: 12, minute: 0, second: 0, nanosecond: 0)!
let endTime = calendar.dateWithEra(1, year: 2016, month: 6, day: 28, hour: 14, minute: 0, second: 0, nanosecond: 0)!

let formatter = NSDateComponentsFormatter()
formatter.allowedUnits = [.Hour, .Minute]
formatter.allowsFractionalUnits = true
formatter.unitsStyle = .Short
formatter.maximumUnitCount = 1

print("Complete next task:", formatter.stringFromDate(startTime, toDate: endTime)!)

它可以处理多个区域设置,为您处理单数(1 hr)和复数(2 hrs)。