Swift/SwiftUI:Swift中的周/日期管理
我正在开发一个健身应用程序,用户可以选择他想锻炼的日子 当他打开应用程序时,我想向他展示本周的情况,在那里他可以观察训练课程安排的日期 如果他是从美国来的,我想给他看一个星期,从周日开始。对于欧盟用户来说,应该从周一开始Swift/SwiftUI:Swift中的周/日期管理,swift,swiftdate,Swift,Swiftdate,我正在开发一个健身应用程序,用户可以选择他想锻炼的日子 当他打开应用程序时,我想向他展示本周的情况,在那里他可以观察训练课程安排的日期 如果他是从美国来的,我想给他看一个星期,从周日开始。对于欧盟用户来说,应该从周一开始 是否有办法根据用户的位置/地理位置获取“当前”周日期?考虑到在适当的位置一周从哪一天开始。我试图为你的问题找到解决方案。我认为这应该奏效: // Define a function that returns the following seven dates, given a
是否有办法根据用户的位置/地理位置获取“当前”周日期?考虑到在适当的位置一周从哪一天开始。我试图为你的问题找到解决方案。我认为这应该奏效:
// 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)
//定义一个函数,给定开始日期,返回以下七个日期
func GetWeekdate(起始日期:日期,带日历:日历)->[日期]{
变量工作日:[日期]=[]
对于0中的i..我试图为您的问题找到解决方案。我认为这应该有效:
// 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)
//定义一个函数,给定开始日期,返回以下七个日期
func GetWeekdate(起始日期:日期,带日历:日历)->[日期]{
变量工作日:[日期]=[]
对于0..中的i,使用
如果返回1,那么星期天是一周的第一天
如果返回2,则星期一是一周的第一天
您可以通过手动设置区域设置来测试这一点
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)")
使用
如果返回1,那么星期天是一周的第一天
如果返回2,则星期一是一周的第一天
您可以通过手动设置区域设置来测试这一点
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)")
你应该阅读日历
课程。你应该阅读日历
课程。