如何快速获取本周的所有天数 [英] How to get all days in current week in swift
本文介绍了如何快速获取本周的所有天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在申请,我需要获取当前一周中所有日子的一年中的哪一天.为此,我正在寻找类似于以下的结果(今天是 3 月 23 日星期四)
I am making an application where I need to get the day of the year for all days in the current week. To achieve this, I am looking for a result similar to below (Today is Thursday the 23rd of March)
Monday = 79
Tuesday = 80
Wednesday = 81
Thursday = 82
Friday = 83
可以包括周六和周日,但是我的申请只需要工作日而不是周末.今天是第82天
Saturday and Sunday can be included, however my application only needs weekdays rather then weekends. Today is day 82
推荐答案
要获取星期几,是:
let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
let dayOfWeek = calendar.component(.weekday, from: today)
let weekdays = calendar.range(of: .weekday, in: .weekOfYear, for: today)!
let days = (weekdays.lowerBound ..< weekdays.upperBound)
.compactMap { calendar.date(byAdding: .day, value: $0 - dayOfWeek, to: today) } // use `flatMap` in Xcode versions before 9.3
.filter { !calendar.isDateInWeekend($0) }
要将其显示为Thursday = 82",则为
To display that as "Thursday = 82", it is
let formatter = DateFormatter()
formatter.dateFormat = "eeee' = 'D"
for date in days {
print(formatter.string(from: date))
}
或者
let strings = days.map { formatter.string(from: $0) }
这篇关于如何快速获取本周的所有天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文