Help, please, make a function on Swift that returns the difference in days between two dates.

func dateDiff (pastDate: Date, nowDate: Date) -> Int { ... return ... } 

Incoming type may not be a Date .

Thank.

  • What does "maybe not a date" mean? - VAndrJ
  • The input parameter type can be used any. Those. You can transfer 2 dates to a function in any form, it doesn’t matter to me, most importantly, I want to understand how to calculate the difference in days - beginner ios developer

1 answer 1

You can get the difference between dates:

 let dateDiff = Calendar.current.dateComponents([.day], from: date1, to: date2).day 

You can arrange in the form of an extension to the Date :

 extension Date { func days(to secondDate: Date, calendar: Calendar = Calendar.current) -> Int { return calendar.dateComponents([.day], from: self, to: secondDate).day! // Здесь force unwrap, так как в компонентах указали .day и берем day } } let dateDiff = date1.days(to: date2)