查找任何日期的下一个最接近的特定日期的NSDate [英] Find NSDate for the next closest specific day of week for any date
问题描述
假设今天是星期三。我可以将 NSDate
分解为 NSDateComponents
,但是我需要找到 NSDate
和下一个即将星期一。如果今天是星期一,那么下一个即将到来的星期一是今天。实现此目标的正确方法是什么?
Let's suppose that today is Wednesday. I can break an NSDate
down into NSDateComponents
, but I need to find the NSDate
with the next upcoming Monday. If today is Monday, then the next upcoming Monday is today. What's the right way to achieve this?
推荐答案
您可以使用 nextDateAfterDate:
方法在 NSCalendar
对象上实现,
You can use nextDateAfterDate:
method on NSCalendar
object to achieve this,
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 时,工作日符号变为
Here, is a simple method to find next monday. If today is Monday the following function returns today or else the closest next Monday. Note that it uses en_POSIX_US such that the days can be matched. When the locale is en_POSIX_US, weekdays symbols become,
["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
,以下是这几天的使用方式。
And, here is how this days could be used,
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!)
这篇关于查找任何日期的下一个最接近的特定日期的NSDate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!