I have output 2019-11-23
and today's date 2019-11-4
. How do I calculate the number of days remaining for these two dates? the output should be
19d5h
Try using DateFormatter
and DateComponents
to get this working.
Get the Date
instances from String
using DateFormatter
and then get day
and hour
components using DateComponents
, i.e.
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
if let d1 = dateFormatter.date(from: "2019-11-23"), let d2 = dateFormatter.date(from: "2019-11-4") {
let components = Calendar.current.dateComponents([.day, .hour], from: d2, to: d1)
print(components.day, components.hour)
}