Swift 3 - find number of calendar days between two dates

前端 未结 11 1994
别跟我提以往
别跟我提以往 2020-12-12 23:51

The way I did this in Swift 2.3 was:

let currentDate         = NSDate()
let currentCalendar     = NSCalendar.currentCalendar()

var startDate : NSDate?
var e         


        
相关标签:
11条回答
  • 2020-12-13 00:21

    If someone would need to display all time units e.g "hours minutes seconds" not just "hours". Let's say the time difference between two dates is 1hour 59minutes 20seconds. This function will display "1h 59m 20s".

    Here is my code:

    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'hh:mm:ss"
    let start = dateFormatter.date(from: "2019-01-31T07:45:00")!
    let end = dateFormatter.date(from: "2019-03-01T06:30:00")!
    print("Date Difference :   ", end.offsetFrom(date: start))
    

    Function Definition:

    extension Date {
    
        func offsetFrom(date : Date) -> String {
    
            let dayHourMinuteSecond: Set = [.day, .hour, .minute, .second]
            let difference = NSCalendar.current.dateComponents(dayHourMinuteSecond, from: date, to: self);
    
            let seconds = "\(difference.second ?? 0)s"
            let minutes = "\(difference.minute ?? 0)m" + " " + seconds
            let hours = "\(difference.hour ?? 0)h" + " " + minutes
            let days = "\(difference.day ?? 0)d" + " " + hours
    
            if let day = difference.day, day          > 0 { return days }
            if let hour = difference.hour, hour       > 0 { return hours }
            if let minute = difference.minute, minute > 0 { return minutes }
            if let second = difference.second, second > 0 { return seconds }
            return ""
        }
    }
    
    0 讨论(0)
  • 2020-12-13 00:22

    In Swift 4 there is a simple one-liner to get the number of days (or any other DateComponent) between two dates:

    let diffInDays = Calendar.current.dateComponents([.day], from: dateA, to: dateB).day
    
    0 讨论(0)
  • 2020-12-13 00:25
    private func days(actual day1:[Int],expect day2:[Int]) -> Int {
    
            let dateFormatter = DateFormatter()
            dateFormatter.dateFormat = "yyyy-MM-dd"
    
            let first = "\(day1[2])-\(day1[1])-\(day1[0])"
            let firstDate = dateFormatter.date(from:first)!
            let last = "\(day2[2])-\(day2[1])-\(day2[0])"
            let lastDate = dateFormatter.date(from:last)!
    
            let currentCalendar = NSCalendar.current
    
            let components = currentCalendar.dateComponents([.day], from: firstDate, to: lastDate)
    
            return components.day!
        }
    

    Another approach to compare with components of day month year

    Usage:

    Input the dates in following format

    [dd, mm, yyyy]
    [9, 6, 2017]
    [6, 6, 2017]
    
    0 讨论(0)
  • 2020-12-13 00:26
    import Foundation
    
    extension DateComponents {
    
        func dateComponentsToTimeString() -> String {
    
            var hour = "\(self.hour!)"
            var minute = "\(self.minute!)"
            var second = "\(self.second!)"
    
            if self.hour! < 10 { hour = "0" + hour }
            if self.minute! < 10 { minute = "0" + minute }
            if self.second! < 10 { second = "0" + second }
    
            let str = "\(hour):\(minute):\(second)"
            return str
        }
    
    }
    
    extension Date {
    
        func offset(from date: Date)-> DateComponents {
            let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .month, .year])
            let differenceOfDate = Calendar.current.dateComponents(components, from: date, to: self)
            return differenceOfDate
        }
    }
    

    Use:

     var durationString: String {
            return self.endTime.offset(from: self.startTime).dateComponentsToTimeString()
        }
    
    0 讨论(0)
  • 2020-12-13 00:29

    Found this on a different thread, but it was finally the most simple solution for me using Swift 4:

    let previousDate = ENTER DATE HERE
    let now = Date()
    
    let formatter = DateComponentsFormatter()
    formatter.unitsStyle = .brief // May delete the word brief to let Xcode show you the other options
    formatter.allowedUnits = [.month, .day, .hour]
    formatter.maximumUnitCount = 1   // Show just one unit (i.e. 1d vs. 1d 6hrs)
    
    let stringDate = formatter.string(from: previousDate, to: now)
    
    0 讨论(0)
提交回复
热议问题