Swift 判断是否为同一周

2018-11-03  本文已影响0人  Just丶Go
// MARK: - 分类.  时间间隔判断
extension Date {
    // MARK: - private method
    // MARK: 两个日期的间隔
    private func daysBetweenDate(toDate: Date) -> Int {
        let components = Calendar.current.dateComponents([.day], from: self, to: toDate)
        return abs(components.day!)
    }
    
    // MARK: 日期对应当周的周几. 周一为开始, 周天为结束
    private func dayForWeekAtIndex() -> Int {
        let components = Calendar.current.dateComponents([.weekday], from: self)
        
        return (components.weekday! - 1) == 0 ? 7 : (components.weekday! - 1)
    }
    
    // MARK: - public method
    // MARK: 判断是否为同一周
    func isSameWeek(date: Date) -> Bool {
        let differ = self.daysBetweenDate(toDate: date)
        // 判断哪一个日期更早
        let compareResult = Calendar.current.compare(self, to: date, toGranularity: Calendar.Component.day)
        
        // 获取更早的日期
        var earlyDate: Date
        if compareResult == ComparisonResult.orderedAscending {
            earlyDate = self
        }else {
            earlyDate = date
        }
        print(earlyDate)
        
        let indexOfWeek = earlyDate.dayForWeekAtIndex()
        let result = differ + indexOfWeek
        
        return result > 7 ? false : true
    }
上一篇下一篇

猜你喜欢

热点阅读