calendar获取本周一的日期_如何快速获取本周的星期一日期

小编典典

我写了Date扩展名以获取某个工作日的Date,这就是在Swift 5中使用它的简便性

Date.today() // Oct 15, 2019 at 9:21 AM

Date.today().next(.monday) // Oct 21, 2019 at 9:21 AM

Date.today().next(.sunday) // Oct 20, 2019 at 9:21 AM

Date.today().previous(.sunday) // Oct 13, 2019 at 9:21 AM

Date.today().previous(.monday) // Oct 14, 2019 at 9:21 AM

Date.today().previous(.thursday) // Oct 10, 2019 at 9:21 AM

Date.today().next(.thursday) // Oct 17, 2019 at 9:21 AM

Date.today().previous(.thursday,

considerToday: true) // Oct 10, 2019 at 9:21 AM

Date.today().next(.monday)

.next(.sunday)

.next(.thursday) // Oct 31, 2019 at 9:21 AM

这是日期扩展,

extension Date {

static func today() -> Date {

return Date()

}

func next(_ weekday: Weekday, considerToday: Bool = false) -> Date {

return get(.next,

weekday,

considerToday: considerToday)

}

func previous(_ weekday: Weekday, considerToday: Bool = false) -> Date {

return get(.previous,

weekday,

considerToday: considerToday)

}

func get(_ direction: SearchDirection,

_ weekDay: Weekday,

considerToday consider: Bool = false) -> Date {

let dayName = weekDay.rawValue

let weekdaysName = getWeekDaysInEnglish().map { $0.lowercased() }

assert(weekdaysName.contains(dayName), "weekday symbol should be in form \(weekdaysName)")

let searchWeekdayIndex = weekdaysName.firstIndex(of: dayName)! + 1

let calendar = Calendar(identifier: .gregorian)

if consider && calendar.component(.weekday, from: self) == searchWeekdayIndex {

return self

}

var nextDateComponent = calendar.dateComponents([.hour, .minute, .second], from: self)

nextDateComponent.weekday = searchWeekdayIndex

let date = calendar.nextDate(after: self,

matching: nextDateComponent,

matchingPolicy: .nextTime,

direction: direction.calendarSearchDirection)

return date!

}

}

// MARK: Helper methods

extension Date {

func getWeekDaysInEnglish() -> [String] {

var calendar = Calendar(identifier: .gregorian)

calendar.locale = Locale(identifier: "en_US_POSIX")

return calendar.weekdaySymbols

}

enum Weekday: String {

case monday, tuesday, wednesday, thursday, friday, saturday, sunday

}

enum SearchDirection {

case next

case previous

var calendarSearchDirection: Calendar.SearchDirection {

switch self {

case .next:

return .forward

case .previous:

return .backward

}

}

}

}

2020-07-07

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值