Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of dates for given day of the week Swift

Tags:

ios

swift3

I need to get the List of dates for the given date of the week.

As an example : If user select the random date from picker Like 2017-6-7, I needs to get and display the dates of the week. [2017-6-4, 2017-6-5, 2017-6-6, 2017-6-7, 2017-6-8, 2017-6-9, 2017-6-10]

I couldn't find any solution on the internet.

Thank you

like image 823
gamal Avatar asked Dec 10 '22 11:12

gamal


2 Answers

Try this:

let dateInWeek = Date()//7th June 2017

let calendar = Calendar.current
let dayOfWeek = calendar.component(.weekday, from: dateInWeek)
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: dateInWeek)!
let days = (weekdays.lowerBound ..< weekdays.upperBound)
    .compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: dateInWeek) }

print(days)

It will give you this:

4 June 2017(Sunday)
5 June 2017
6 June 2017
7 June 2017
8 June 2017
9 June 2017
10 June 2017(Saturday)


Start fromMonday
The above is default behavior for my calendar that's why it is starting from Sunday.
If you want start from Monday then do this change:

let dayOfWeek = calendar.component(.weekday, from: dateInWeek) - 1

It depends on which locale your calendar is in.

like image 77
D4ttatraya Avatar answered Dec 31 '22 19:12

D4ttatraya


This is a starting point using the date math skills of Calendar

var calendar = Calendar.current
calendar.firstWeekday = 1 // adjust first weekday if necessary
var startOfWeek = Date()
var interval : TimeInterval = 0.0
_ = calendar.dateInterval(of:.weekOfYear, start: &startOfWeek, interval: &interval, for: Date())
for i in 0..<7 {
    print(calendar.date(byAdding: .day, value: i, to: startOfWeek)!)
}
like image 24
vadian Avatar answered Dec 31 '22 19:12

vadian