是一个日期在同一个星期,一个月,另一个日期的快照

时间:2017-04-27 16:47:07

标签: ios swift date

了解日期与同一周(或年或月)的最佳方式是什么,最好是扩展名,仅使用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]);
}

请不要提出将DateNSDate

联系起来的解决方案

2 个答案:

答案 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
    }
}