简体   繁体   English

Swift/SwiftUI:swift 中的星期/日期管理

[英]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如果它返回 1,那么星期日是一周的第一天

If it returns 2, then Monday is the first day of week.如果它返回 2,那么星期一是一周的第一天。

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)")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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