Reputation: 29
Is possible to find total number of hours when a user has selected a future time for example, if the current time is 12:00PM and user select to finish a task in the next 2 hours 2:00PM as the target time, how can I represent those 2 hours like this " Time to complete next task 2Hours"
Here is what I have so far:
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")
This is what prints out:
Complete next task 20HR
Upvotes: 1
Views: 44
Reputation: 93151
Use 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)!)
It can handle multiple locales, take care of singular (1 hr
) and plural (2 hrs
) for you.
Upvotes: 1