Swift days between two NSDates

后端 未结 27 1206
清歌不尽
清歌不尽 2020-11-27 13:30

I\'m wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the \"new\" Cocoa?

E.g. like in Ruby I would do:

相关标签:
27条回答
  • 2020-11-27 13:58

    This is an updated version of Emin's answer for Swift 5 that incorporates the suggestion to use noon instead of midnight as the definitive time for comparing days. It also handles the potential failure of various date functions by returning an optional.

        ///
        /// This is an approximation; it does not account for time differences. It will set the time to 1200 (noon) and provide the absolute number
        /// of days between now and the given date. If the result is negative, it should be read as "days ago" instead of "days from today."
        /// Returns nil if something goes wrong initializing or adjusting dates.
        ///
    
        func daysFromToday() -> Int?
        {
            let calendar = NSCalendar.current
    
            // Replace the hour (time) of both dates with noon. (Noon is less likely to be affected by DST changes, timezones, etc. than midnight.)
            guard let date1 = calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: Date())),
                  let date2 = calendar.date(bySettingHour: 12, minute: 00, second: 00, of: calendar.startOfDay(for: self)) else
            {
                return nil
            }
    
            return calendar.dateComponents([.day], from: date1, to: date2).day
        }
    
    0 讨论(0)
  • 2020-11-27 13:58

    easier option would be to create a extension on Date

    public extension Date {
    
            public var currentCalendar: Calendar {
                return Calendar.autoupdatingCurrent
            }
    
            public func daysBetween(_ date: Date) -> Int {
                let components = currentCalendar.dateComponents([.day], from: self, to: date)
                return components.day!
            }
        }
    
    0 讨论(0)
  • 2020-11-27 13:59

    Swift 3.2

    extension DateComponentsFormatter {
        func difference(from fromDate: Date, to toDate: Date) -> String? {
            self.allowedUnits = [.year,.month,.weekOfMonth,.day]
            self.maximumUnitCount = 1
            self.unitsStyle = .full
            return self.string(from: fromDate, to: toDate)
        }
    }
    
    0 讨论(0)
提交回复
热议问题