美文网首页
Swift 判断是否为同一周

Swift 判断是否为同一周

作者: Just丶Go | 来源:发表于2018-11-03 19:20 被阅读0次
    // 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
        }
    

    相关文章

      网友评论

          本文标题:Swift 判断是否为同一周

          本文链接:https://www.haomeiwen.com/subject/xiflxqtx.html