//
|
// Date+Extension.swift
|
// DateDemo
|
//
|
// Created by Sweet on 2019/3/10.
|
// Copyright © 2019年 Sweet. All rights reserved.
|
//
|
|
import UIKit
|
extension Date {
|
//MARK: - 获取日期各种值
|
//MARK: 年
|
func year() ->Int {
|
let calendar = NSCalendar.current
|
let com = calendar.dateComponents([.year,.month,.day], from: self)
|
return com.year!
|
}
|
//MARK: 月
|
func month() ->Int {
|
let calendar = NSCalendar.current
|
let com = calendar.dateComponents([.year,.month,.day], from: self)
|
return com.month!
|
|
}
|
//MARK: 日
|
func day() ->Int {
|
let calendar = NSCalendar.current
|
let com = calendar.dateComponents([.year,.month,.day], from: self)
|
return com.day!
|
|
}
|
//MARK: 星期几
|
func weekDay()->Int{
|
let interval = Int(self.timeIntervalSince1970)
|
let days = Int(interval/86400) // 24*60*60
|
let weekday = ((days + 4)%7+7)%7
|
return weekday == 0 ? 7 : weekday
|
}
|
//MARK: 当月天数
|
func countOfDaysInMonth() ->Int {
|
let calendar = Calendar(identifier:Calendar.Identifier.gregorian)
|
let range = (calendar as NSCalendar?)?.range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: self)
|
return (range?.length)!
|
|
}
|
//MARK: 当月第一天是星期几
|
func firstWeekDay() ->Int {
|
//1.Sun. 2.Mon. 3.Thes. 4.Wed. 5.Thur. 6.Fri. 7.Sat.
|
let calendar = Calendar(identifier:Calendar.Identifier.gregorian)
|
let firstWeekDay = (calendar as NSCalendar?)?.ordinality(of: NSCalendar.Unit.weekday, in: NSCalendar.Unit.weekOfMonth, for: self)
|
return firstWeekDay! - 1
|
|
}
|
//MARK: - 日期的一些比较
|
//是否是今天
|
func isToday()->Bool {
|
let calendar = NSCalendar.current
|
let com = calendar.dateComponents([.year,.month,.day], from: self)
|
let comNow = calendar.dateComponents([.year,.month,.day], from: Date())
|
return com.year == comNow.year && com.month == comNow.month && com.day == comNow.day
|
}
|
//是否是这个月
|
func isThisMonth()->Bool {
|
let calendar = NSCalendar.current
|
let com = calendar.dateComponents([.year,.month,.day], from: self)
|
let comNow = calendar.dateComponents([.year,.month,.day], from: Date())
|
return com.year == comNow.year && com.month == comNow.month
|
}
|
}
|
|
class DateClass {
|
//MARK: - 当前时间相关
|
//MARK: 今年
|
static func currentYear() ->Int {
|
let calendar = NSCalendar.current
|
let com = calendar.dateComponents([.year,.month,.day], from: Date())
|
return com.year!
|
}
|
//MARK: 今月
|
static func currentMonth() ->Int {
|
let calendar = NSCalendar.current
|
let com = calendar.dateComponents([.year,.month,.day], from: Date())
|
|
return com.month!
|
|
}
|
//MARK: 今日
|
static func currentDay() ->Int {
|
let calendar = NSCalendar.current
|
let com = calendar.dateComponents([.year,.month,.day], from: Date())
|
return com.day!
|
|
}
|
//MARK: 今天星期几
|
static func currentWeekDay()->Int{
|
let interval = Int(Date().timeIntervalSince1970)
|
let days = Int(interval/86400) // 24*60*60
|
let weekday = ((days + 4)%7+7)%7
|
return weekday == 0 ? 7 : weekday
|
}
|
//MARK: 本月天数
|
static func countOfDaysInCurrentMonth() ->Int {
|
let calendar = Calendar(identifier:Calendar.Identifier.gregorian)
|
let range = (calendar as NSCalendar?)?.range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: Date())
|
return (range?.length)!
|
|
}
|
//MARK: 当月第一天是星期几
|
static func firstWeekDayInCurrentMonth() ->Int {
|
//星期和数字一一对应 星期日:7
|
let dateFormatter = DateFormatter()
|
dateFormatter.dateFormat = "yyyy-MM"
|
let date = dateFormatter.date(from: String(Date().year())+"-"+String(Date().month()))
|
let calender = Calendar(identifier:Calendar.Identifier.gregorian)
|
let comps = (calender as NSCalendar?)?.components(NSCalendar.Unit.weekday, from: date!)
|
var week = comps?.weekday
|
if week == 1 {
|
week = 8
|
}
|
return week! - 1
|
}
|
// 获取当前小时
|
static func getTimes() -> [Int] {
|
|
var timers: [Int] = [] // 返回的数组
|
|
let calendar: Calendar = Calendar(identifier: .gregorian)
|
var comps: DateComponents = DateComponents()
|
comps = calendar.dateComponents([.year,.month,.day, .weekday, .hour, .minute,.second], from: Date())
|
|
timers.append(comps.year! % 2000) // 年 ,后2位数
|
timers.append(comps.month!) // 月
|
timers.append(comps.day!) // 日
|
timers.append(comps.hour!) // 小时
|
timers.append(comps.minute!) // 分钟
|
timers.append(comps.second!) // 秒
|
timers.append(comps.weekday! - 1) //星期
|
|
return timers;
|
}
|
//MARK: - 获取指定日期各种值
|
//根据年月得到某月天数
|
static func getCountOfDaysInMonth(year:Int,month:Int) ->Int{
|
let dateFormatter = DateFormatter()
|
dateFormatter.dateFormat = "yyyy-MM"
|
let date
|
= dateFormatter.date(from: String(year)+"-"+String(month))
|
let calendar = Calendar(identifier:Calendar.Identifier.gregorian)
|
let range = (calendar as NSCalendar?)?.range(of: NSCalendar.Unit.day, in: NSCalendar.Unit.month, for: date!)
|
return (range?.length)!
|
}
|
//MARK: 根据年月得到某月第一天是周几
|
static func getfirstWeekDayInMonth(year:Int,month:Int) -> Int{
|
let dateFormatter = DateFormatter()
|
dateFormatter.dateFormat = "yyyy-MM"
|
let date
|
= dateFormatter.date(from: String(year)+"-"+String(month))
|
let calendar = Calendar(identifier:Calendar.Identifier.gregorian)
|
let comps = (calendar as NSCalendar?)?.components(NSCalendar.Unit.weekday, from: date!)
|
let week = comps?.weekday
|
return week! - 1
|
}
|
|
//MARK: 获取指定日期星期几 dateTime: 年-月-日
|
|
/// 指定日期星期几 dateTime: 年-月-日
|
static func getWeekDay(dateTime:String,dateFormat:String = "yyyy-MM-dd")->String{
|
var weekStr = ""
|
let dateFmt = DateFormatter()
|
dateFmt.dateFormat = dateFormat
|
let date = dateFmt.date(from: dateTime)
|
let interval = Int(date!.timeIntervalSince1970) + NSTimeZone.local.secondsFromGMT()
|
let days = Int(interval/86400) // 24*60*60
|
let weekday = ((days + 4)%7+7)%7
|
|
switch weekday {
|
case 0:
|
weekStr = "周日"
|
case 1:
|
weekStr = "周一"
|
case 2:
|
weekStr = "周二"
|
case 3:
|
weekStr = "周三"
|
case 4:
|
weekStr = "周四"
|
case 5:
|
weekStr = "周五"
|
case 6:
|
weekStr = "周六"
|
case 7:
|
weekStr = "周日"
|
default:
|
break
|
}
|
return weekStr
|
}
|
// 获取指定日期星期几(数字) dateTime: 年-月-日
|
static func getWeekDayNum(dateTime:String)->Int{
|
let dateFmt = DateFormatter()
|
dateFmt.dateFormat = "yyyy-MM-dd "
|
let date = dateFmt.date(from: dateTime)
|
let interval = Int(date!.timeIntervalSince1970) + NSTimeZone.local.secondsFromGMT()
|
let days = Int(interval/86400) // 24*60*60
|
let weekday = ((days + 4)%7+7)%7
|
return weekday
|
}
|
|
// 获取指定日期星期几(数字) dateTime: 时间戳
|
static func getWeekDayNumhhmmss(dateTime:String)->Int{
|
let time = self.timeStampToStringDetail(dateTime)
|
let dateFmt = DateFormatter()
|
dateFmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
|
let date = dateFmt.date(from: time)
|
let interval = Int(date!.timeIntervalSince1970) + NSTimeZone.local.secondsFromGMT()
|
let days = Int(interval/86400) // 24*60*60
|
let weekday = ((days + 4)%7+7)%7
|
return weekday
|
}
|
// 获取指定日期星期几(数字) dateTime: 时间错
|
static func getWeekDayStemp(dateTime:String)->Int{
|
|
let dateFmt = DateFormatter()
|
dateFmt.dateFormat = "yyyy-MM-dd HH:mm:ss"
|
let date = dateFmt.date(from: dateTime)
|
let interval = Int(date!.timeIntervalSince1970) + NSTimeZone.local.secondsFromGMT()
|
let days = Int(interval/86400) // 24*60*60
|
let weekday = ((days + 4)%7+7)%7
|
return weekday
|
}
|
|
/// date转日期字符串
|
static func dateToDateString(_ date:Date, dateFormat:String) -> String {
|
let timeZone = NSTimeZone.local
|
let formatter = DateFormatter()
|
formatter.timeZone = timeZone
|
formatter.dateFormat = dateFormat
|
|
let date = formatter.string(from: date)
|
return date
|
}
|
|
/// 日期字符串转date
|
static func dateStringToDate(_ dateStr:String) ->Date {
|
let dateFormatter = DateFormatter()
|
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
|
dateFormatter.dateFormat = "yyyy-MM-dd"
|
let date = dateFormatter.date(from: dateStr)
|
return date!
|
}
|
/// 时间字符串转date
|
static func timeStringToDate(_ dateStr:String) ->Date {
|
|
let dateFormatter = DateFormatter()
|
// dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
|
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
|
let date = dateFormatter.date(from: dateStr)
|
return date!
|
}
|
|
/// 计算天数差
|
static func dateDifference(_ dateA:Date, from dateB:Date) -> Double {
|
let interval = dateA.timeIntervalSince(dateB)
|
return interval/86400
|
|
}
|
|
/// 比较时间先后
|
static func compareOneDay(oneDay:Date, withAnotherDay anotherDay:Date) -> Int {
|
let dateFormatter:DateFormatter = DateFormatter()
|
dateFormatter.dateFormat = "yyyy-MM-dd"
|
let oneDayStr:String = dateFormatter.string(from: oneDay)
|
let anotherDayStr:String = dateFormatter.string(from: anotherDay)
|
let dateA = dateFormatter.date(from: oneDayStr)
|
let dateB = dateFormatter.date(from: anotherDayStr)
|
let result:ComparisonResult = (dateA?.compare(dateB!))!
|
//Date1 is in the future
|
if(result == ComparisonResult.orderedDescending ) {
|
return 1
|
|
}
|
//Date1 is in the past
|
else if(result == ComparisonResult.orderedAscending) {
|
return 2
|
|
}
|
//Both dates are the same
|
else {
|
return 0
|
}
|
}
|
|
//MARK: 时间与时间戳之间的转化
|
/// 将时间转换为时间戳 带格式的
|
static func stringToTimeStamp(stringTime:String,fmatter:String = "yyyy-MM-dd" )->Int {
|
let dfmatter = DateFormatter()
|
dfmatter.dateFormat = fmatter
|
|
dfmatter.locale = Locale.current
|
|
let date = dfmatter.date(from: stringTime)
|
|
let dateStamp:TimeInterval = date!.timeIntervalSince1970
|
|
let dateSt:Int = Int(dateStamp)
|
|
return dateSt * 1000
|
}
|
|
|
/// 将时间转换为时间带格式的
|
static func stringToTimeStampFormatter(_ stringTime:String,dfmatterStr:String)->Int {
|
let dfmatter = DateFormatter()
|
var matterStr = dfmatterStr
|
if matterStr == "" || matterStr.isEmpty{
|
matterStr = "yyyy-MM-dd HH:mm:ss"
|
}
|
dfmatter.dateFormat = matterStr
|
|
dfmatter.locale = Locale.current
|
|
let date = dfmatter.date(from: stringTime)
|
|
let dateStamp:TimeInterval = date?.timeIntervalSince1970 ?? 0
|
|
let dateSt:Int = Int(dateStamp)
|
|
return dateSt
|
}
|
///将时间戳转换为年月日
|
static func timeStampToString(_ timeStamp:String,dateFormat:String = "yyyy-MM-dd HH:mm:ss" )->String {
|
var timeStampInt = ""
|
if timeStamp.count > 10 {
|
timeStampInt = "\(timeStamp.wy_toInt() / 1000)"
|
}else{
|
timeStampInt = timeStamp
|
}
|
let string = NSString(string: timeStampInt)
|
let timeSta:TimeInterval = string.doubleValue
|
let dfmatter = DateFormatter()
|
dfmatter.dateFormat = dateFormat
|
let date = Date(timeIntervalSince1970: timeSta)
|
return dfmatter.string(from: date)
|
}
|
|
/// 时间戳 判断是否是今天
|
/// - Parameter timeStamp: 时间戳
|
// static func isToday(timeStamp:String) -> Bool {
|
// var isTod = false
|
// var timeStampInt = ""
|
// if timeStamp.count > 10 {
|
// timeStampInt = "\(timeStamp.wy_toInt() / 1000)"
|
// }else{
|
// timeStampInt = timeStamp
|
// }
|
// let string = NSString(string: timeStampInt)
|
// let timeSta:TimeInterval = string.doubleValue
|
// let dfmatter = DateFormatter()
|
//
|
// let date = Date(timeIntervalSince1970: timeSta)
|
// isTod = date.isToday
|
//
|
// return isTod
|
// }
|
///将时间戳转换为具体时间
|
static func timeStampToStringDetail(_ timeStamp:String)->String {
|
var timeStampInt = ""
|
if timeStamp.count > 10 {
|
timeStampInt = "\(timeStamp.wy_toInt() / 1000)"
|
}else{
|
timeStampInt = timeStamp
|
}
|
|
let string = NSString(string: timeStampInt)
|
|
let timeSta:TimeInterval = string.doubleValue
|
|
let dfmatter = DateFormatter()
|
dfmatter.dateFormat="yyyy-MM-dd HH:mm:ss"
|
let date = Date(timeIntervalSince1970: timeSta)
|
return dfmatter.string(from: date)
|
}
|
///将时间戳转换为时分秒
|
static func timeStampToHHMMSS(_ timeStamp:String)->String {
|
let string = NSString(string: timeStamp)
|
let timeSta:TimeInterval = string.doubleValue
|
let dfmatter = DateFormatter()
|
dfmatter.dateFormat="HH:mm:ss"
|
let date = Date(timeIntervalSince1970: timeSta)
|
return dfmatter.string(from: date)
|
}
|
///获取系统的当前时间戳
|
static func getStamp()->Int{
|
//获取当前时间戳
|
let date = Date()
|
let timeInterval:Int = Int(date.timeIntervalSince1970)
|
return timeInterval * 1000
|
}
|
///月份数字转汉字
|
static func numberToChina(monthNum:Int) -> String {
|
let ChinaArray = ["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"]
|
let ChinaStr:String = ChinaArray[monthNum - 1]
|
return ChinaStr
|
|
}
|
/// 数字前补0
|
static func add0BeforeNumber(_ number:Int) -> String {
|
if number >= 10 {
|
return String(number)
|
}else{
|
return "0" + String(number)
|
}
|
}
|
|
/// 将时间显示为(几分钟前,几小时前,几天前)
|
static func compareCurrentTime(str:String) -> String {
|
var timeStamp = 0.0
|
if str.count > 10 {
|
timeStamp = str.wy_toDouble() / 1000.0
|
}else{
|
timeStamp = str.wy_toDouble()
|
}
|
let timeDate = Date(timeIntervalSince1970: timeStamp)
|
|
let timeInterval = NSDate().timeIntervalSince(timeDate)
|
|
var temp:Double = 0
|
|
var result:String = ""
|
|
if timeInterval/60 < 1 {
|
|
result = "刚刚"
|
|
}else if (timeInterval/60) < 60{
|
|
temp = timeInterval/60
|
|
result = "\(Int(temp))分钟前"
|
|
}else if timeInterval/60/60 < 24 {
|
|
temp = timeInterval/60/60
|
|
result = "\(Int(temp))小时前"
|
|
}else if timeInterval/(24 * 60 * 60) < 7 {
|
|
temp = timeInterval / (24 * 60 * 60)
|
|
result = "\(Int(temp))天前"
|
}
|
else if timeInterval/(24 * 60 * 60) < 30{
|
temp = timeInterval / (24 * 60 * 60*7)
|
result = "\(Int(temp))周前"
|
// let string = str.substring(to: 10).components(separatedBy: "-")
|
// result = "\(string[1])月\(string.last ?? "")日"
|
}
|
// }else if timeInterval/(30 * 24 * 60 * 60) < 12 {
|
//
|
// temp = timeInterval/(30 * 24 * 60 * 60)
|
//
|
// result = "\(Int(temp))个月前"
|
//
|
// }
|
else{
|
result = DateClass.timeStampToString(str, dateFormat: "yyyy-MM-dd HH:mm:ss")
|
|
}
|
return result
|
|
}
|
/// 比较两个日期大小 yyyy-MM-dd HH:mm
|
static func compareDateStr(aDate: String, bDate: String,dateFormatStr:String) -> Int {
|
var aa: Int?
|
|
let dateformater = DateFormatter()
|
dateformater.dateFormat = dateFormatStr
|
var dta = Date()
|
var dtb = Date()
|
|
if let date = dateformater.date(from: aDate ) {
|
dta = date
|
}
|
if let date = dateformater.date(from: bDate ) {
|
dtb = date
|
}
|
let result: ComparisonResult = dta.compare(dtb)
|
|
if result == ComparisonResult.orderedSame {
|
aa = 0
|
// 相等 aa=0
|
} else if result == ComparisonResult.orderedAscending {
|
//bDate比aDate大
|
aa = 1
|
} else if result == ComparisonResult.orderedDescending {
|
//bDate比aDate小
|
aa = -1
|
}
|
return aa ?? -2
|
}
|
/// 获取下一个月 日期
|
static func getNextMonth(date: Date) -> Date{
|
var greCalendar = Calendar(identifier: .gregorian)
|
if let time = NSTimeZone(name: "UTC") {
|
greCalendar.timeZone = time as TimeZone
|
}
|
var comps = greCalendar.dateComponents([.year, .month, .day], from: date)
|
(comps.month)! += 1
|
return greCalendar.date(from: comps)!
|
}
|
/// 获取 上一个月 日期
|
static func getLastMonth(date: Date) -> Date{
|
var greCalendar = Calendar(identifier: .gregorian)
|
if let time = NSTimeZone(name: "UTC") {
|
greCalendar.timeZone = time as TimeZone
|
}
|
var comps = greCalendar.dateComponents([.year, .month, .day], from: date)
|
(comps.month)! -= 1
|
return greCalendar.date(from: comps)!
|
}
|
|
}
|
|
/// 获取星座
|
struct Constellation {
|
|
private enum ConstellationType:String {
|
case 白羊座, 金牛座, 双子座, 巨蟹座, 狮子座, 处女座,
|
天秤座, 天蝎座, 射手座, 摩羯座, 水瓶座, 双鱼座
|
}
|
|
private static let constellationDict:[ConstellationType :String] = [.白羊座: "3.21-4.19",
|
.金牛座: "4.20-5.20",
|
.双子座: "5.21-6.21",
|
.巨蟹座: "6.22-7.22",
|
.狮子座: "7.23-8.22",
|
.处女座: "8.23-9.22",
|
.天秤座: "9.23-10.23",
|
.天蝎座: "10.24-11.22",
|
.射手座: "11.23-12.21",
|
.摩羯座: "12.22-1.19",
|
.水瓶座: "1.20-2.18",
|
.双鱼座: "2.19-3.20"]
|
|
/// 日期 -> 星座
|
/// - parameter date: 日期
|
/// - returns: 星座名称
|
public static func calculateWithDate(date: Date) -> String? {
|
|
let timeInterval = date.timeIntervalSince1970
|
let OneDay:Double = 86400
|
|
let currConstellation = constellationDict.filter {
|
|
let timeRange = getTimeRange(date: date, timeRange: $1)
|
let startTime = timeRange.0
|
let endTime = timeRange.1 + OneDay
|
|
return timeInterval > startTime && timeInterval < endTime
|
} // 摩羯座这家伙跨年必定不满足
|
|
return currConstellation.first?.key.rawValue ?? "摩羯座"
|
}
|
|
/// f.获取开始、结束时间
|
private static func getTimeRange(date:Date, timeRange: String) -> (TimeInterval, TimeInterval) {
|
|
/// f.1 获取当前年份
|
func getCurrYear(date:Date) -> String {
|
|
let dm = DateFormatter()
|
dm.dateFormat = "yyyy."
|
let currYear = dm.string(from: date)
|
return currYear
|
}
|
|
/// f.2 日期转换当前时间戳
|
func toTimeInterval(dateStr: String) -> TimeInterval? {
|
|
let dm = DateFormatter()
|
dm.dateFormat = "yyyy.MM.dd"
|
|
let date = dm.date(from: dateStr)
|
let interval = date?.timeIntervalSince1970
|
|
return interval
|
}
|
|
let timeStrArr = timeRange.components(separatedBy: "-")
|
let dateYear = getCurrYear(date: date)
|
let startTimeStr = dateYear + timeStrArr.first!
|
let endTimeStr = dateYear + timeStrArr.last!
|
|
let startTime = toTimeInterval(dateStr: startTimeStr)!
|
let endTime = toTimeInterval(dateStr: endTimeStr)!
|
|
return (startTime, endTime)
|
}
|
}
|