如何快速获取当前一周的所有天数 [英] 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
推荐答案
要获取一周中的工作日,它是:
To get the weekdays of the week, it is:
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) }
要显示为星期四= 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屋!
查看全文