Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

ios - How to get dates for every thursday or other day of week in specific month?

I want to get date of particular day for every week.

Suppose I have a date: 2017-04-13. It is an April, and 13 April is Thursday. I need to get every date in April which is Thursday.

How can I do this?

The output should be: 2017-04-06, 2017-04-13, 2017-04-20, 2017-04-27

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Short solution:

// Get current calendar and current date let calendar = Calendar.current let now = Date() // Get the current date components for year, month, weekday and weekday ordinal var components = calendar.dateComponents([.year, .month, .weekdayOrdinal, .weekday], from: now) // get the range (number of occurrences) of the particular weekday in the month let range = calendar.range(of: .weekdayOrdinal, in: .month, for: now)! // Loop thru the range, set the components to the appropriate weekday ordinal and get the date for ordinal in range.lowerBound.. Be aware that print prints dates always in UTC.

Edit:

range(of: .weekdayOrdinal, in: .month does not work, it returns 1..<6 regardless of the date.

This is a working alternative. It checks if the date exceeds the month bounds

// Get current calendar and date for 2017/4/13
let calendar = Calendar.current
let april13Components = DateComponents(year:2017, month:4, day:13)
let april13Date = calendar.date(from: april13Components)!

// Get the current date components for year, month, weekday and weekday ordinal
var components = calendar.dateComponents([.year, .month, .weekdayOrdinal, .weekday], from: april13Date)

// Loop thru the range, set the components to the appropriate weekday ordinal and get the date
for ordinal in 1..<6 { // maximum 5 occurrences
    components.weekdayOrdinal = ordinal
    let date = calendar.date(from: components)!
    if calendar.component(.month, from: date) != components.month! { break }
    print(calendar.date(from: components)!)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...