Swift days between two NSDates

2020-01-24 20:29发布

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:

(end_date - start_date).to_i

25条回答
疯言疯语
2楼-- · 2020-01-24 20:47

2017 version, copy and paste

func simpleIndex(ofDate: Date) -> Int {

    // index here just means today 0, yesterday -1, tomorrow 1 etc.

    let c = Calendar.current
    let todayRightNow = Date()

    let d = c.date(bySetting: .hour, value: 13, of: ofDate)
    let t = c.date(bySetting: .hour, value: 13, of: todayRightNow)

    if d == nil || today == nil {

        print("weird problem simpleIndex#ofDate")
        return 0
    }

    let r = c.dateComponents([.day], from: today!, to: d!)
    // yesterday is negative one, tomorrow is one

    if let o = r.value(for: .day) {

        return o
    }
    else {

        print("another weird problem simpleIndex#ofDate")
        return 0
    }
}
查看更多
\"骚年 ilove
3楼-- · 2020-01-24 20:50

You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00 and 2015-01-02 09:00, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours).

If your purpose is to get the exact day number between two dates, you can work around this issue like this:

// Assuming that firstDate and secondDate are defined
// ...

let calendar = NSCalendar.currentCalendar()

// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDayForDate(firstDate)
let date2 = calendar.startOfDayForDate(secondDate)

let flags = NSCalendarUnit.Day
let components = calendar.components(flags, fromDate: date1, toDate: date2, options: [])

components.day  // This will return the number of day(s) between dates

Swift 3 and Swift 4 Version

let calendar = Calendar.current

// Replace the hour (time) of both dates with 00:00
let date1 = calendar.startOfDay(for: firstDate)
let date2 = calendar.startOfDay(for: secondDate)

let components = calendar.dateComponents([.day], from: date1, to: date2)
查看更多
地球回转人心会变
4楼-- · 2020-01-24 20:50

This returns an absolute difference in days between some Date and today:

extension Date {
  func daysFromToday() -> Int {
    return abs(Calendar.current.dateComponents([.day], from: self, to: Date()).day!)
  }
}

and then use it:

if someDate.daysFromToday() >= 7 {
  // at least a week from today
}
查看更多
啃猪蹄的小仙女
5楼-- · 2020-01-24 20:50

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!
        }
    }
查看更多
一夜七次
6楼-- · 2020-01-24 20:51

All answer is good. But for Localizations we need calculates a number of decimal days in between two dates. so we can provide the sustainable decimal format.

// This method returns the fractional number of days between to dates
func getFractionalDaysBetweenDates(date1: Date, date2: Date) -> Double {

    let components = Calendar.current.dateComponents([.day, .hour], from: date1, to: date2)

    var decimalDays = Double(components.day!)
    decimalDays += Double(components.hour!) / 24.0

    return decimalDays
}
查看更多
虎瘦雄心在
7楼-- · 2020-01-24 20:56

Erin's method updated to Swift 3, This shows days from today (disregarding time of day)

func daysBetweenDates( endDate: Date) -> Int 
    let calendar: Calendar = Calendar.current 
    let date1 = calendar.startOfDay(for: Date()) 
    let date2 = calendar.startOfDay(for: secondDate) 
    return calendar.dateComponents([.day], from: date1, to: date2).day! 
}
查看更多
登录 后发表回答