public extension Date {
var day: Int {
return Calendar.current.component(Calendar.Component.day, from: self)
}
var month: Int {
return Calendar.current.component(Calendar.Component.month, from: self)
}
var year: Int {
return Calendar.current.component(Calendar.Component.year, from: self)
}
/// 是否在未来
var isInFuture: Bool {
return self > Date()
}
/// 是否在过去
var isInPast: Bool {
return self < Date()
}
/// 是否在本天
var isInToday: Bool {
return self.day == Date().day && self.month == Date().month && self.year == Date().year
}
/// 是否在本月
var isInMonth: Bool {
return self.month == Date().month && self.year == Date().year
}
//获得当前月份第一天星期几
var weekdayForFirstday: Int {
var calendar = Calendar.current
calendar.firstWeekday = 1
var comp = calendar.dateComponents([.year, .month, .day], from: self)
comp.day = 1
let firstDayInMonth = calendar.date(from: comp)!
let weekday = calendar.ordinality(of: Calendar.Component.weekday, in: Calendar.Component.weekOfMonth, for: firstDayInMonth)
return weekday! - 1
}
// 获得一个月总天数
var daysInMonth: Int {
return Calendar.current.range(of: Calendar.Component.day, in: Calendar.Component.month, for: self)!.count
}
/// 获取其他月的数据
///
/// - Parameter poor: 与当前的date相差几个月 (-1---上月, 1---下月)
/// - Returns: 目标date
func getOtherMonthDate(_ poor: Int) -> Date {
var dateComponents = DateComponents()
dateComponents.month = poor
return Calendar.current.date(byAdding: dateComponents, to: self)!
}
}
网友评论