Tom
Tom

Reputation: 4033

Convert DateComponent to Int

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'

Upvotes: 3

Views: 2261

Answers (1)

ielyamani
ielyamani

Reputation: 18591

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!

Upvotes: 4

Related Questions