I am making an application where I need to get the weeks of the year for all days in the current year. To achieve this, I am looking for a result similar to below
30 Dec - 05 Jan
06 Jan - 12 Jan
13 Jan - 19 Jan
.
.
.
28 Dec - 03 Jan
I am making an application where I need to get the weeks of the year for all days in the current year. To achieve this, I am looking for a result similar to below
30 Dec - 05 Jan
06 Jan - 12 Jan
13 Jan - 19 Jan
.
.
.
28 Dec - 03 Jan
You can use the suggested extension in this thread: How to get start and end of the week in swift? To iterate the weeks, and then just print the value with your desired formatter:
let calendar = Calendar.current
let currentYear = calendar.component(.year, from: Date())
let lastDayOfTheYear = calendar.date(from: DateComponents(year: currentYear, month: 12, day: 31))
var currentDate = calendar.date(from: DateComponents(year: currentYear, month: 1, day: 1))
while currentDate! < lastDayOfTheYear! {
let startDay = currentDate!.startOfWeek!.formatted()
let endDay = currentDate!.endOfWeek!.formatted()
print("\(startDay) - \(endDay)")
currentDate = calendar.date(byAdding: .weekOfYear, value: 1, to: currentDate!)
}
extension Date {
func formatted() -> String {
let formatter = DateFormatter()
formatter.dateStyle = .long
return formatter.string(from: self)
}
var startOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 1, to: sunday)
}
var endOfWeek: Date? {
let gregorian = Calendar(identifier: .gregorian)
guard let sunday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
return gregorian.date(byAdding: .day, value: 7, to: sunday)
}
}
prints:
December 30, 2019 - January 5, 2020
January 6, 2020 - January 12, 2020
...
December 21, 2020 - December 27, 2020
December 28, 2020 - January 3, 2021