Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert DateComponent to Int

Tags:

ios

swift

To get the difference between two dates in days I did the following:

let calendar = Calendar.current
guard let startDate = timeStartDate else { return }
let pastTime = calendar.dateComponents([.day], from: startDate, to: Date())

Now I'm trying to calculate something with pastTime hence I need the Int. How can I convert a value of type DateComponent to Int?

So far using Int(pastTime) I got the following error:

Initializer 'init(_:)' requires that 'DateComponents' conform to 'BinaryInteger'

like image 407
Tom Avatar asked Nov 28 '25 02:11

Tom


1 Answers

pastTime is of type DateComponents and thus it can't be passed as a parameter to the Int initializer.

Use the .day property of DateComponents:

let numberOfDays = pastTime.day 

Which is an optional Int, but since you've specified the day component in dateComponents:from:to, you could safely unwrap it as noted by @vadian:

let numberOfDays = pastTime.day!
like image 114
ielyamani Avatar answered Nov 29 '25 19:11

ielyamani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!