Home > Software design >  week range in swift with weekYear
week range in swift with weekYear

Time:09-21

Could you help me, I don't know what configuration I'm missing

I want to obtain the week range for the year 2021, week 37 in Mexico that starts from Monday to Sunday but it seems that my code brings another week number and also starts from Sunday to Monday

The week in Mexico starts from

Week 37 September 13, 2021 September 19, 2021

enter image description here

var weekNumber: Int = 0

var calendar = Calendar(identifier: .gregorian)
calendar.firstWeekday = 2
calendar.minimumDaysInFirstWeek = 4
let year = calendar.component(.year, from: Date())

weekNumber  = calendar.component(.weekOfYear, from: Date())
print("weekNumber",weekNumber)
print("Date",Date())
let startComponents = DateComponents(weekOfYear: weekNumber, yearForWeekOfYear: year)
let startDate = calendar.date(from: startComponents)!
let endComponents = DateComponents(day:7, second: 0)
let endDate = calendar.date(byAdding: endComponents, to: startDate)!
print("startDate",startDate)
print("endDate",endDate)

enter image description here

CodePudding user response:

You are using the wrong calendar. The first weekday of Gregorian calendar is Sunday, what you need is to use ISO8601 calendar. Also when using weekOfYear you would use yearForWeekOfYear:


let now = Date()
var calendar = Calendar(identifier: .iso8601)
let yearForWeekOfYear = calendar.component(.yearForWeekOfYear, from: now)
let weekNumber  = calendar.component(.weekOfYear, from: now)
print("weekNumber", weekNumber)
print("Date", now.description(with: .current))
let startDate = DateComponents(calendar: calendar, weekOfYear: weekNumber, yearForWeekOfYear: yearForWeekOfYear).date!
let endDate = calendar.date(byAdding: .weekOfYear, value: 1, to: startDate)!
print("startDate", startDate.description(with: .current))
print("endDate", endDate.description(with: .current))

This will print:

weekNumber 37
Date Sunday, September 19, 2021 at 9:07:02 PM Brasilia Standard Time
startDate Monday, September 13, 2021 at 12:00:00 AM Brasilia Standard Time
endDate Monday, September 20, 2021 at 12:00:00 AM Brasilia Standard Time

  • Related