Search code examples
swiftswiftdate

Swift/SwiftUI: week/date management in swift


I'm working on fitness app where users selects the days he wants to exercise on.

When he opens the app I wanna shown him the current week where he can observe the days his training sessions are scheduled for.

If he is from the US i wanna show him a week starting from Sunday. For EU users it should start with Monday.

Is there any way to get the "current" week dates depending on user's location/geo? Taking into account what day does the week start with in appropriate location.


Solution

  • I tried to find a solution for your question. I think this should work:

    // Define a function that returns the following seven dates, given a start date
    func getWeekDates(of startDate: Date, with calender: Calendar) -> [Date] {
        var weekDates: [Date] = []
        for i in 0..<7 {
            weekDates.append(calendar.date(byAdding: .day, value: i, to: startDate)!)
        }
        return weekDates
    }
    
    // This should automatically take the right calendar for the user's locale
    // If you want to specify the day weeks start with manually, choose .gregorian or .iso8601:
    // .gregorian starts on Sunday, .iso8601 starts on Monday
    let calendar = Calendar.current
    
    let startOfCurrentWeek = calendar.date(from: calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: Date()))
    
    let currentWeekDates = getWeekDates(of: startOfCurrentWeek!, with: calendar)
    

    Hope this helps.