了解日期与同一周(或年或月)的最佳方式是什么,最好是扩展名,仅使用Swift ?
作为一个例子,在Objective-C中我有
- (BOOL)isSameWeekAs:(NSDate *)date {
NSDateComponents *otherDay = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:self];
NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitEra | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:date];
return ([today weekOfYear] == [otherDay weekOfYear] &&
[today year] == [otherDay year] &&
[today era] == [otherDay era]);
}
请不要提出将Date
与NSDate
答案 0 :(得分:65)
您可以使用日历方法isDate(equalTo:granularity:)
进行检查,如下所示:
extension Date {
func isInSameWeek(date: Date) -> Bool {
return Calendar.current.isDate(self, equalTo: date, toGranularity: .weekOfYear)
}
func isInSameMonth(date: Date) -> Bool {
return Calendar.current.isDate(self, equalTo: date, toGranularity: .month)
}
func isInSameYear(date: Date) -> Bool {
return Calendar.current.isDate(self, equalTo: date, toGranularity: .year)
}
func isInSameDay(date: Date) -> Bool {
return Calendar.current.isDate(self, equalTo: date, toGranularity: .day)
}
var isInThisWeek: Bool {
return isInSameWeek(date: Date())
}
var isInToday: Bool {
return Calendar.current.isDateInToday(self)
}
var isInTheFuture: Bool {
return Date() < self
}
var isInThePast: Bool {
return self < Date()
}
}
答案 1 :(得分:8)
您可以使用此扩展程序,该扩展程序基于您提供的Objective-C代码:
extension Date {
func hasSame(_ components: Calendar.Component..., as date: Date, using calendar: Calendar = .autoupdatingCurrent) -> Bool {
return components.filter { calendar.component($0, from: date) != calendar.component($0, from: self) }.isEmpty
}
}
此处的默认日历为autoupdatingCurrent
,因此如果用户更改日历,则会相应更新。它还使用可变参数组件,允许您指定任意数量的组件,而无需将它们包装到数组中。
使用示例:
let date1 = Date()
let date2 = Date()
let date3 = Date(timeIntervalSince1970: 30.0)
print(date1.hasSame(.weekOfYear, .day, .hour, as: date2)) // true
print(date1.hasSame(.weekOfYear, as: date3)) // false
修改
正如@Leo Dabus指出的那样,我们可以使用set here而不是array / variadic参数 - 这样我们就可以避免多次比较相同的组件,如果用户将一些重复项传递给方法:
extension Date {
func hasSame(_ components: Set<Calendar.Component>, as date: Date, using calendar: Calendar = .autoupdatingCurrent) -> Bool {
return components.filter { calendar.component($0, from: date) != calendar.component($0, from: self) }.isEmpty
}
}