Swift 3 - find number of calendar days between two dates

前端 未结 11 1992
别跟我提以往
别跟我提以往 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: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([.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()
        }
    

提交回复
热议问题