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

时间:2015-07-31 07:24:43

标签: cocoa cocoa-touch nsdate date-arithmetic

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

3 个答案:

答案 0 :(得分:24)

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

let now = Date() // today

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

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

这是一个查找下一个星期一的简单方法。如果今天是星期一,则以下函数今天返回,否则最接近下周一。请注意,它使用 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!)

答案 1 :(得分:2)

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

否则你可以使用这个

WebElement lastDay = driver.findElement(By.xpath("((//table//tr)[last()]//td[not (contains(@class, 'ui-datepicker-other-month'))])[last()]"));

答案 2 :(得分:-4)

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

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)