swift - Swift/SwiftUI:快速的星期/日期管理
问题描述
我正在开发健身应用程序,用户可以在其中选择他想锻炼的日子。
当他打开应用程序时,我想向他展示当前的一周,他可以在其中观察他的培训课程安排的日期。
如果他来自美国,我想从周日开始给他看一周。对于欧盟用户,它应该从星期一开始。
有没有办法根据用户的位置/地理位置获取“当前”周日期?考虑到一周从哪一天在适当的位置开始。
解决方案
我试图为您的问题找到解决方案。我认为这应该有效:
// 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)
希望这可以帮助。
推荐阅读
- ruby - 如何在我的 ruby 程序中添加无限数量的人
- xamarin.forms - 使用与 Xamarin 表单异步时的 MoveNext 错误
- mysql - MYSQL 使用别名作为列以防万一
- ios - 查找 iOS 设备摄像头与用户面部之间的距离
- audio - 浏览器音频的不准确 Hz 检测
- android - Android Studio 3.2:如何记住 Android XML 代码风格?
- google-cloud-composer - 使用 MsSqlOperator 时没有名为 pymssql 的模块
- image - Xamarin Forms XAML 图像控件已停止工作
- ruby-on-rails - Ruby on Rails/PostGRE - 没有运算符匹配给定的名称和参数类型。错误
- javascript - 单行的Angular6多个ngFor-如何在一个ngFor中传递两个值