简体   繁体   中英

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.

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.

Use

Calendar.current.firstWeekday

If it returns 1, then Sunday is the first day of week

If it returns 2, then Monday is the first day of week.

You can test this by setting locale manually

var calendar = Calendar.current

calendar.locale = Locale(identifier: "en_GB")
print("\(calendar.locale!) starts on day \(calendar.firstWeekday)")
// en_GB starts on day 2

calendar.locale = Locale(identifier: "en_US")
print("\(calendar.locale!) starts on day \(calendar.firstWeekday)")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM