简体   繁体   中英

dateComponents() from... to in days shows from now to tomorrow as 0 days?

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 - ie regardless of the timestamp of my target date - the number of days to that day remaining constant until midnight is reached.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM