[swift3]二個日期的比較

  • 98
  • 0

程式中碰到二個日期的比較

 


let date = Date()
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
formatter.locale = Locale.current
formatter.timeZone = TimeZone(abbreviation:"GMT")

let result = formatter.string(from: date)
let result2 = formatter.date(from: result)

print(date)     //date,   "2017-04-26 07:34:14 +0000\n"
print(result)   //string, "2017-04-26\n"
print(result2!) //date,   "2017-04-26 00:00:00 +0000\n"

let str = "2017-04-25"
let temp = formatter.date(from:str)

if let result3 = temp {
  
    print(result3)//date, "2017-04-25 00:00:00 +0000\n"
    
    let numOfDays = result3.daysBetweenDate(toDate: result2!)
    
    print(numOfDays)  //1

    //numOfDays = 0, 代表result2 = result3
    //numOfDays > 0, 代表result2 > result3
    //numOfDays < 0, 代表result2 < result3
}


extension Date {
    func daysBetweenDate(toDate:Date) -> Int {
        let components = Calendar.current.dateComponents([.day], from: self, to:toDate)
        
        return components.day ?? 0
    }
}