我想使用Swift 3创建一系列Date对象,想知道是否有一个API可以简化我想做的事情,例如:
我想做的事情之一是为1年(1月到12月)生成一系列日期,每个日期代表每个月的1号。
我知道我可以在一个循环中完成所有这些,就像这样……
func monthsInYear() {
var calendar = Calendar.current
let date = Date()
let monthsOfYearRange = calendar.range(of: .month, in: .year, for: date)
print(monthsOfYearRange as Any)
if let monthsOfYearRange = monthsOfYearRange {
let year = calendar.component(.year, from: date)
for monthOfYear in (monthsOfYearRange.lowerBound..<monthsOfYearRange.upperBound) {
let components = DateComponents(year: year, month: monthOfYear)
guard let date = Calendar.current.date(from: components) else { continue }
print(date.description(with: Locale.current))
}
}
}
它产生以下输出...
Sunday, January 1, 2017 at 12:00:00 AM Eastern Standard Time
Wednesday, February 1, 2017 at 12:00:00 AM Eastern Standard Time
Wednesday, March 1, 2017 at 12:00:00 AM Eastern Standard Time
Saturday, April 1, 2017 at 12:00:00 AM Eastern Daylight Time
Monday, May 1, 2017 at 12:00:00 AM Eastern Daylight Time
Thursday, June 1, 2017 at 12:00:00 AM Eastern Daylight Time
Saturday, July 1, 2017 at 12:00:00 AM Eastern Daylight Time
Tuesday, August 1, 2017 at 12:00:00 AM Eastern Daylight Time
Friday, September 1, 2017 at 12:00:00 AM Eastern Daylight Time
Sunday, October 1, 2017 at 12:00:00 AM Eastern Daylight Time
Wednesday, November 1, 2017 at 12:00:00 AM Eastern Daylight Time
Friday, December 1, 2017 at 12:00:00 AM Eastern Standard Time
然而,我正在寻找一种更简单更简洁的方法来做到这一点。我想在给定月份的周,给定周的天,给定天的小时中做同样的事情,我可以做到,但它使用相同的循环。
1条答案
按热度按时间qojgxg4l1#
这就是我所做的-坚持“循环”:S
它在运行时生成以下输出: