首页 > 解决方案 > Swift/SwiftUI:快速的星期/日期管理

问题描述

我正在开发健身应用程序,用户可以在其中选择他想锻炼的日子。

当他打开应用程序时,我想向他展示当前的一周,他可以在其中观察他的培训课程安排的日期。

如果他来自美国,我想从周日开始给他看一周。对于欧盟用户,它应该从星期一开始。

有没有办法根据用户的位置/地理位置获取“当前”周日期?考虑到一周从哪一天在适当的位置开始。

标签: swiftswiftdate

解决方案


我试图为您的问题找到解决方案。我认为这应该有效:

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

希望这可以帮助。


推荐阅读