// 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 判断是否为同一周
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...