ios – 是另一个日期的同一周,月,年的日期

前端之家收集整理的这篇文章主要介绍了ios – 是另一个日期的同一周,月,年的日期前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
知道某个日期是在同一周(或年份或月份)中的最佳方式是什么,最好是使用扩展,并且只使用 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]);
}

请不要向NSDate提出解决日期的解决方

解决方法

您可以使用日历方法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,toGranularity: .month)
    }
    func isInSameYear(date: Date) -> Bool {
        return Calendar.current.isDate(self,toGranularity: .year)
    }
    func isInSameDay(date: Date) -> Bool {
        return Calendar.current.isDate(self,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()
    }
}
原文链接:/iOS/333240.html

猜你在找的iOS相关文章