Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get all days in current week in swift

I am making an application where I need to get the day of the year for all days in the current week. To achieve this, I am looking for a result similar to below (Today is Thursday the 23rd of March)

Monday = 79
Tuesday = 80
Wednesday = 81
Thursday = 82
Friday = 83

Saturday and Sunday can be included, however my application only needs weekdays rather then weekends. Today is day 82

like image 912
iProgram Avatar asked Mar 23 '17 16:03

iProgram


4 Answers

I had problems with adapting Rob's solution for when the week starts on Monday. This solution adapts to your calendar.firstWeekday setting.

var calendar = Calendar.autoupdatingCurrent
calendar.firstWeekday = 2 // Start on Monday (or 1 for Sunday)
let today = calendar.startOfDay(for: Date())
var week = [Date]()
if let weekInterval = calendar.dateInterval(of: .weekOfYear, for: today) {
    for i in 0...6 {
        if let day = calendar.date(byAdding: .day, value: i, to: weekInterval.start) {
            week += [day]
        }
    }
}
return week
like image 104
Benjamin Angeria Avatar answered Oct 04 '22 11:10

Benjamin Angeria


I made a small extension on Calendar, which might be helpful for anyone else looking for a more functional solution to this.

import Foundation

extension Calendar {
  func intervalOfWeek(for date: Date) -> DateInterval? {
    dateInterval(of: .weekOfYear, for: date)
  }

  func startOfWeek(for date: Date) -> Date? {
    intervalOfWeek(for: date)?.start
  }

  func daysWithSameWeekOfYear(as date: Date) -> [Date] {
    guard let startOfWeek = startOfWeek(for: date) else {
      return []
    }

    return (0 ... 6).reduce(into: []) { result, daysToAdd in
      result.append(Calendar.current.date(byAdding: .day, value: daysToAdd, to: startOfWeek))
    }
    .compactMap { $0 }
  }
}
like image 34
Lutzifer Avatar answered Oct 04 '22 13:10

Lutzifer


To get the weekdays of the week, it is:

let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dayOfWeek = calendar.component(.weekday, from: today)
let days = calendar.range(of: .weekday, in: .weekOfYear, for: today)!
    .compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) }
    .filter { !calendar.isDateInWeekend($0) }

To display that as "Thursday = 82", it is

let formatter = DateFormatter()
formatter.dateFormat = "eeee' = 'D"
for date in days {
    print(formatter.string(from: date))
}

Or

let strings = days.map { formatter.string(from: $0) }
like image 31
Rob Avatar answered Oct 04 '22 12:10

Rob


You could also use enumerateDates like this:

func getAllDaysOfTheCurrentWeek() -> [Date] {
    var dates: [Date] = []
    guard let dateInterval = Calendar.current.dateInterval(of: .weekOfYear,
                                                           for: Date()) else {
        return dates
    }
    
    Calendar.current.enumerateDates(startingAfter: dateInterval.start,
                                    matching: DateComponents(hour:0),
                                    matchingPolicy: .nextTime) { date, _, stop in
            guard let date = date else {
                return
            }
            if date <= dateInterval.end {
                dates.append(date)
            } else {
                stop = true
            }
    }
    
    return dates
}
like image 28
Sebastian Boldt Avatar answered Oct 04 '22 12:10

Sebastian Boldt