Home > Software design >  dateComponents() from... to in days shows from now to tomorrow as 0 days?
dateComponents() from... to in days shows from now to tomorrow as 0 days?

Time:08-01

I have datecomponent objects that represent some time in the future. I want to calculate how many dates from now until that date. I'm also including representation of the dates simply as dates. What I'm finding is that when I am trying to show how many there are to a date that is 'tomorrow' it's showing 0. To my mind it should be showing 1. I can try a hacky way of just adding 1 to my count but I'm wondering is it because it's trying to round to the nearest 24 hours or something? If so how can I 'fix' it?

Here is my sample code: let myPreviousRelevantDate = self.datePickerOutlet.date

let nextDate = Date(timeInterval: Double(86400 * (myDurationInDaysAsInt)), since: myPreviousRelevantDate!)

let daysToNextDate = Calendar.current.dateComponents([.day], from: Date(), to: nextDate).day!

What I'd like to avoid is the number of days to the target date changing during the day also - i.e. regardless of the timestamp of my target date - the number of days to that day remaining constant until midnight is reached.

CodePudding user response:

If your intent is to calculate the number of days using a timeless calendrical calculation what you need is to use noon time. Note that not every day has 24 hours, you should always use calendar method to add days to a date:

extension Date {
    var noon: Date {
        Calendar(identifier: .iso8601)
            .date(
                bySettingHour: 12,
                minute: 0,
                second: 0,
                of: self
            )!
    }
}

let daysToNextDate = Calendar.current.dateComponents([.day], from: Date().noon, to: nextDate.noon).day!
  • Related