How to determine if an NSDate is today?

前端 未结 20 2093
礼貌的吻别
礼貌的吻别 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 19:02

    The correct and safe solution without force-unwrapping, working on Swift 2.2 and before iOS 8:

    func isToday() -> Bool {
        let calendar = NSCalendar.currentCalendar()
        if #available(iOS 8.0, *) {
            return calendar.isDateInToday(self)
        }
    
        let todayComponents = calendar.components([.Era, .Year, .Month, .Day], fromDate:NSDate())
        let dayComponents = calendar.components([.Era, .Year, .Month, .Day], fromDate:self)
    
        guard let today = calendar.dateFromComponents(todayComponents),
            day = calendar.dateFromComponents(dayComponents) else {
            return false
        }
    
        return today.compare(day) == .OrderedSame
    }
    

提交回复
热议问题