【发布时间】:2017-07-21 13:30:41
【问题描述】:
我想显示 星期一 到 星期五 的日期/天,不包括 星期六/星期日,如下图所示。
我的场景:
- 屏幕加载时应显示当前周。
- 在上一个按钮上单击 (DisplayedWeek - 1)
- 在 Next 按钮上单击 (DisplayedWeek + 1)。
我的工作,
经过一些研究,这是我尝试过的。
let calendar = Calendar.current
let currentDate = calendar.startOfDay(for: Date())
/* value = 0 for current,
value = 1 for next,
value = -1 for previous week.
*/
let nextWeek:Date = calendar.date(byAdding: .weekOfMonth, value: 1, to: currentDate)! as Date
let dayOfWeek = calendar.component(.weekday, from: nextWeek)
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: nextWeek)!
let days = (weekdays.lowerBound ..< weekdays.upperBound).flatMap {
calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: nextWeek)
}.filter { !calendar.isDateInWeekend($0) }
// Week Days from monday to friday
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd"
for date in days {
print(formatter.string(from: date))
}
在我的情况下,如果这一天是 星期六 或 星期日,它应该在下周显示,但它显示的是同一周。
【问题讨论】:
-
您有哪些“时区相关问题”?请出示minimal reproducible example,清楚地说明问题。
-
@MartinR 添加了一些细节
标签: ios swift nsdateformatter