查找任何日期的下一个最接近的特定星期几的 NSDate

Find NSDate for the next closest specific day of week for any date

假设今天是星期三。我可以将 NSDate 分解为 NSDateComponents,但我需要在下一个 即将到来的 星期一找到 NSDate。如果今天是星期一,那么下一个 即将到来的 星期一就是今天。实现这一目标的正确方法是什么?

您可以使用 NSDateComponents 获取工作日并计算间隔天数,然后使用 NSDate 中的 dateByAddingTimeInterval ,如下所示:

let now = NSDate()
let calendar: NSDateComponents = NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitWeekday, fromDate: now)
let weekday = calendar.weekday  // 1 = Sunday, 2 = Monday

// You get input the weekday here and calculate the interval

// exmaple for moving to the next day
let expectedDate = now.dateByAddingTimeInterval(1 * 24 * 60 * 60)

// exmaple for moving to yesterday
let yesterday = now.dateByAddingTimeInterval(-1 * 24 * 60 * 60)

您可以在 NSCalendar 对象上使用 nextDateAfterDate: 方法来实现此目的,

let now = Date() // today

var matchingComponents = DateComponents()
matchingComponents.weekday = 2 // Monday

let comingMonday =  Calendar.current.nextDate(after: now,
                                              matching: matchingComponents,
                                              matchingPolicy:.nextTime)

这里是一个简单的查找下周一的方法。如果今天是星期一,则以下函数 returns 今天或最近的下星期一。请注意,它使用 en_POSIX_US 以便可以匹配日期。当区域设置为 en_POSIX_US 时,工作日符号变为,

["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]

而且,这几天可以这样使用,

func findNext(_ day: String, afterDate date: Date) -> Date? {

    var calendar = Calendar.current
    calendar.locale = Locale(identifier: "en_US_POSIX")

    let weekDaySymbols = calendar.weekdaySymbols
    let indexOfDay = weekDaySymbols.index(of: day)

    assert(indexOfDay != nil, "day passed should be one of \(weekDaySymbols), invalid day: \(day)")

    let weekDay = indexOfDay! + 1

    let components = calendar.component(.weekday, from: date)

    if components == weekDay {
        return date
    }

    var matchingComponents = DateComponents()
    matchingComponents.weekday = weekDay // Monday

    let nextDay = calendar.nextDate(after: date,
                                    matching: matchingComponents,
                                    matchingPolicy:.nextTime)
    return nextDay!
}


let nextMonday = findNext("Monday", afterDate: Date())
let mondayAfterThat = findNext("Monday", afterDate: nextMonday!)

let thursday = findNext("Thursday", afterDate: mondayAfterThat!)

对于目标 iOS >= 8 使用 GeneratorOfOne 的解决方案

否则你可以使用这个

let now = NSDate()
var lastMonday:NSDate?
var nextMonday:NSDate?
var start:NSDate?        

var interval:NSTimeInterval = 0   // holds the length of a week. can differ for Daylight Saving Time
let cal = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)! // have a own calendar object for this calculation to guarantee that the next line does not influence other calculations 
cal.firstWeekday = 2              // make sure first day of week is Monday. 


cal.rangeOfUnit(NSCalendarUnit.CalendarUnitWeekOfMonth, startDate: &lastMonday, interval:&interval, forDate: now)      // monday of current week
nextMonday = lastMonday?.dateByAddingTimeInterval(interval)  // add a weeks length to the last weeks's monday
println(nextMonday)