How to determine if an NSDate is today?

前端 未结 20 2018
礼貌的吻别
礼貌的吻别 2020-11-28 18:20

How to check if an NSDate belongs to today?

I used to check it using first 10 characters from [aDate description]. [[aDate descriptio

20条回答
  •  清酒与你
    2020-11-28 18:47

    Here's my 2 cent answer building on the accepted answer but supporting the newer API as well. Note: I use the Gregorian calendar as most time stamps are GMT but change yours as you see fit

    func isDateToday(date: NSDate) -> Bool {
        let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
        if calendar.respondsToSelector("isDateInToday:") {
            return calendar.isDateInToday(date)
        }
        let dateComponents = NSCalendarUnit.CalendarUnitYear | NSCalendarUnit.CalendarUnitMonth | NSCalendarUnit.CalendarUnitDay
        let today = calendar.dateFromComponents(calendar.components(dateComponents, fromDate: NSDate()))!
        let dateToCompare = calendar.dateFromComponents(calendar.components(dateComponents, fromDate: date))!
    
        return dateToCompare == today
    }
    

提交回复
热议问题