我有两个NSDates。如何比较它们以确定日期是否在同一周内。
我有一个系统,目前检查两个日期是否在同一天内,并且代码如下:
if calan.compareDate(datee, toDate: now, toUnitGranularity: .CalendarUnitDay) == .OrderedSame {
transactionsToday.addObject(transaction)
}else{
println("No transactions today")
}
我将使用哪个UnitGranularity检查两个日期是否共享同一周?
答案 0 :(得分:10)
if calan.compareDate(datee, toDate: now, toUnitGranularity: .CalendarUnitWeekOfYear) == .OrderedSame {
transactionsToday.addObject(transaction)
}else{
println(“No transactions this week")
}
与现在使用.CalendarUnitDay
的方式相同您也可以使用.CalendarUnitWeekOfYear
编辑:
如果你想检查日期是否在一周内,而不是在同一周,你可以得到last-和nextWeekDate
let lastWeekDate = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitWeekOfYear, value: -1, toDate: NSDate(), options: nil)!
当然下周将是
let nextWeekDate = NSCalendar.currentCalendar().dateByAddingUnit(.CalendarUnitWeekOfYear, value: 1, toDate: NSDate(), options: nil)!
然后,您可以查看当前日期是否在这两个日期之间
答案 1 :(得分:1)
如果您使用公历,您可以使用计算一年中的一周并获得这两个日期的年份然后进行比较。
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let date1 = NSDate(timeIntervalSinceNow: 0)
let date2 = NSDate(timeIntervalSinceNow: -10*24*60*60) //10 day earlier.
let weekOfYear1 = calendar!.component(NSCalendarUnit.CalendarUnitWeekOfYear, fromDate: date1)
let weekOfYear2 = calendar!.component(NSCalendarUnit.CalendarUnitWeekOfYear, fromDate: date2)
let year1 = calendar!.component(NSCalendarUnit.CalendarUnitYear, fromDate: date1)
let year2 = calendar!.component(NSCalendarUnit.CalendarUnitYear, fromDate: date2)
if (weekOfYear1 == weekOfYear2
&& year1 == year2
) {
NSLog("Same week")
} else {
NSLog("Other week")
}
答案 2 :(得分:0)
Swift5
我写了一个小扩展,使这个过程更容易一些:
extension Date {
func isTheSame(_ component: Calendar.Component, as date: Date) -> Bool {
return Calendar.current.compare(self, to: date, toGranularity: component) == .orderedSame
}
}
然后您可以简单地执行以下操作:
if firstDate.isTheSame(.week, as: secondDate) {
// Both dates are the same week
} else {
// Dates are different weeks
}
(适用于任何类别,例如:.day、.month、.year 等)