// // Date+Formatter.swift // HPlusFit // // Created by lemo. on 2019/9/15. // Copyright © 2019 lemo. All rights reserved. // import UIKit extension Date { // 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 hour() -> Int { let calendar = NSCalendar.current let com = calendar.dateComponents([.year,.month,.day, .hour], from: self) return com.hour! } // MARK:- 分 func minute() -> Int { let calendar = NSCalendar.current let com = calendar.dateComponents([.year,.month,.day, .hour, .minute], from: self) return com.minute! } // 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 } // MARK:- 是否是这个月 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 } // MARK:- 距离2018-01-01的日,周,月统计量 func getCounts(type: Int) -> Int { let formatter = DateFormatter() formatter.dateFormat = "yyyy-MM-dd" let startDate = formatter.date(from: "2018-01-01") var count: Int = 0 if type == 0 { //日 let comps = Calendar.current.dateComponents([.day], from: startDate!, to: self) count = comps.day! } if type == 1 { //周 let comps = Calendar.current.dateComponents([.day], from: startDate!, to: self) count = comps.day!/7 } if type == 2 { //月 let comps = Calendar.current.dateComponents([.month], from: startDate!, to: self) count = comps.month! } return count } // 本周开始日期(星期天) func startOfThisWeek() -> Date { let calendar = NSCalendar.current let commponets = calendar.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self) let startOfWeek = calendar.date(from: commponets) return startOfWeek! } // 本月开始日期 func startOfCurrentMonth() -> Date { let calendar = NSCalendar.current let components = calendar.dateComponents([.year, .month], from: self) let startOfMonth = calendar.date(from: components)! return startOfMonth } /// 获取偏移月份的日期 /// /// - Parameter offset: 偏移的月份 func getDateFromCurrentMonth(offset: Int) -> Date? { let calendar = Calendar.current var coms = calendar.dateComponents([.year, .month, .day], from: self) coms.month = coms.month! - offset coms.day = 1 return calendar.date(from: coms) } /// 获取这个月有多少天 /// /// - Returns: func getMonthHowManyDay() -> Range { return Calendar.current.range(of: .day, in: .month, for: self)! } /// 获取这个月第一天的日期 /// /// - Returns: func getMonthFirstDay() -> Date? { let calendar = Calendar.current var com = calendar.dateComponents([.year, .month,.day], from: self) com.day = 1 return calendar.date(from: com) } /// 获取这个月最后一天的日期 func getMonthEndDay(returnEndTime:Bool = false) -> Date { let calendar = NSCalendar.current var components = DateComponents() components.month = 1 components.second = -1 components.timeZone = TimeZone.current let endOfMonth = calendar.date(byAdding: components, to: startOfCurrentMonth())! return endOfMonth } /// 获取偏移天数的日期 /// /// - Parameter offset: 偏移天数 /// - Returns: func getDay(offset: Int) -> Date? { let calendar = Calendar.current var com = calendar.dateComponents([.year, .month,.day], from: self) com.day = com.day! + offset return calendar.date(from: com) } func date2String() -> String? { let dateformatter = DateFormatter.init() dateformatter.dateFormat = "yyyy-MM-dd" return dateformatter.string(from: self) } //该时间所在周的第一天日期(2017年12月17日 00:00:00) var startOfWeek: Date { let calendar = NSCalendar.current let components = calendar.dateComponents( Set([.yearForWeekOfYear, .weekOfYear]), from: self) let date = calendar.date(from: components)! return date.getDay(offset: 0)! } //该时间所在周的最后一天日期(2017年12月23日 00:00:00) var endOfWeek: Date { let calendar = NSCalendar.current var components = DateComponents() components.day = 6 return calendar.date(byAdding: components, to: self.startOfWeek)! } /// 转换指定格式字符串 /// - Parameter format: 字符串格式 func tranFormDateStr(format: String) -> String { let dateFormat = DateFormatter() dateFormat.dateFormat = format return dateFormat.string(from: self) } func string(withFormat format: String = "dd/MM/yyyy HH:mm") -> String { let dateFormatter = DateFormatter() dateFormatter.dateFormat = format return dateFormatter.string(from: self) } } class DateClass { // MARK:- 当前年月日字符串 static func todayString() -> String { let dateFormat = DateFormatter() dateFormat.dateFormat = "yyyy-MM-dd" return dateFormat.string(from: Date()) } // MARK:- 当前年月日时分秒字符串 static func todayIntegrateString() -> String { let dateFormat = DateFormatter() // 以中国为准 let locale = Locale(identifier: "zh") dateFormat.locale = locale dateFormat.dateFormat = "yyyy-MM-dd HH:mm:ss" return dateFormat.string(from: Date()) } // MARK:- 获取当前时间戳(秒) static func getNowTimeS() -> Int { let date = Date() let timeInterval:Int = Int(date.timeIntervalSince1970) return timeInterval } // MARK:- 获取当前时区的时间 static func getCurrentTimeZone() -> Date { let date = Date() let zone = TimeZone.current let interval = zone.secondsFromGMT() let nowDate = date.addingTimeInterval(TimeInterval(interval)) return nowDate } // MARK:- 获取0时区的开始时间(2018-5-13 16:00:00) static func getZeroTimeZone() -> Date { let dateFormat = DateFormatter() dateFormat.dateFormat = "yyyy-MM-dd" let todayDate = dateFormat.date(from: DateClass.todayString()) return todayDate! } // MARK:- 获取获取当前时区的开始时间(2018-5-13 00:00:00) static func getCurrentInitTimeZone() -> Date { let dateFormat = DateFormatter() dateFormat.dateFormat = "yyyy-MM-dd" let zone = TimeZone.current dateFormat.timeZone = zone let interval = zone.secondsFromGMT() let todayDate = dateFormat.date(from: DateClass.todayString()) return todayDate!.addingTimeInterval(TimeInterval(interval)) } // MARK:- 将时间戳按指定格式时间输出 13569746264 -> 2018-05-06 static func timestampToStr(_ timestamp: Int, formatStr: String) -> String { let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) let zone = TimeZone.current let dateFormat = DateFormatter() // 以中国为准 let locale = Locale(identifier: "zh") dateFormat.locale = locale dateFormat.dateFormat = formatStr dateFormat.timeZone = zone let str = dateFormat.string(from: date) return str } // MARK:- 将时间格式转换时间戳输出 2018-05-06 -> 13569746264 static func timeStrToTimestamp(_ timeStr: String, formatStr: String) -> Int { let dateFormat = DateFormatter() dateFormat.dateFormat = formatStr let date = dateFormat.date(from: timeStr) ?? Date() let timestamp = Int(date.timeIntervalSince1970) return timestamp } // MARK:- 将制定格式时间转自定义格式时间 2018-05-06 -> 2018-05-06 00:00:00 static func timeStrToTimeStr(_ timeStr: String, formatStr: String, toFormatStr: String) -> String { let timestamp = DateClass.timeStrToTimestamp(timeStr, formatStr: formatStr) return DateClass.timestampToStr(timestamp, formatStr: toFormatStr) } // MARK:- 获取当前时间按指定格式时间输出 static func getCurrentTimeStr(formatStr: String) -> String { let date = Date() let zone = TimeZone.current let dateFormat = DateFormatter() // 以中国为准 let locale = Locale(identifier: "zh") dateFormat.locale = locale dateFormat.dateFormat = formatStr dateFormat.timeZone = zone let str = dateFormat.string(from: date) return str } // MARK:- 距离指定日期偏移天数的日期 static func dateStringOffset(from: String, offset: Int) -> String { let dateFormat = DateFormatter() dateFormat.dateFormat = "yyyy-MM-dd" guard let fromDate = dateFormat.date(from: from) else { return from } var cmps = Calendar.current.dateComponents([.year, .month, .day], from: fromDate) cmps.day = cmps.day! + offset let resultDate = Calendar.current.date(from: cmps) return dateFormat.string(from: resultDate!) } // MARK:- 将指定格式时间字符串转成Date static func getTimeStrToDate(formatStr: String, timeStr: String) -> Date { let zone = TimeZone.current let dateFormat = DateFormatter() dateFormat.dateFormat = formatStr dateFormat.timeZone = zone return dateFormat.date(from: timeStr)! } static func getSpecialDays(dateStr: String, count: Int) -> [String] { var days = [String]() let dateformatter = DateFormatter.init() dateformatter.dateFormat = "yyyy-MM-dd" let date = dateformatter.date(from: dateStr) let calendar = Calendar.current for i in 0.. String { let date:Date = Date.init(timeIntervalSince1970: timeInterval) let formatter = DateFormatter.init() formatter.dateFormat = "yyyy-MM-dd" return formatter.string(from: date as Date) } //指定年月的开始日期 static func startOfMonth(year: Int, month: Int) -> Date { let calendar = NSCalendar.current var startComps = DateComponents() startComps.day = 1 startComps.month = month startComps.year = year let startDate = calendar.date(from: startComps)! return startDate } //指定年月的结束日期 static func endOfMonth(year: Int, month: Int, returnEndTime:Bool = false) -> Date { let calendar = NSCalendar.current var components = DateComponents() components.month = 1 if returnEndTime { components.second = -1 } else { components.day = -1 } let endOfYear = calendar.date(byAdding: components, to: startOfMonth(year: year, month:month))! return endOfYear } /// 单次数据时间展示转换 static func singleDataTimeStr(timestamp: Int64) -> String { let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) let nowYear = Date().year() let hourStr = timestampToHourMinStr(timestamp: timestamp) if date.year() == nowYear { return DateClass.timestampToStr(Int(timestamp), formatStr: "MM/dd") + " \(hourStr)" } return DateClass.timestampToStr(Int(timestamp), formatStr: "yyyy/MM/dd") + " \(hourStr)" } // MARK:- 根据时制转换将时间戳转成时分字符串 9:20 PM / 18:20 static func timestampToHourMinStr(timestamp: Int64) -> String { let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) let zone = TimeZone.current // 时间制 let has24 = getCurrenDateMetric() let formatStr = has24 ? "HH:mm:ss" : "hh:mm:ss aa" let dateFormat = DateFormatter() dateFormat.dateFormat = formatStr dateFormat.timeZone = zone let str = dateFormat.string(from: date) return str } // MARK:- 获取当前时制 false:12小时 true:24小时 static func getCurrenDateMetric() -> Bool { let formatStringForHours = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: NSLocale.current) let containsA = formatStringForHours?.range(of: "a") let has24 = containsA != nil ? false : true return has24 } // MARK:- 根据时制转换将时间戳转成时分字符串 9:20 PM / 18:20 static func timestampToHourMinStr(timestamp: Int) -> String { let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) let zone = TimeZone.current // 时间制 let has24 = getCurrenDateMetric() let formatStr = has24 ? "HH:mm" : "hh:mm aa" let dateFormat = DateFormatter() dateFormat.dateFormat = formatStr dateFormat.timeZone = zone let str = dateFormat.string(from: date) return str } // MARK:- 根据时制转换将时间戳转成时分字符串 9:20:11 PM / 18:20:11 static func timestampToHourMinSecondStr(timestamp: Int) -> String { let date = Date(timeIntervalSince1970: TimeInterval(timestamp)) let zone = TimeZone.current // 时间制 let has24 = getCurrenDateMetric() let formatStr = has24 ? "HH:mm:ss" : "hh:mm:ss aa" let dateFormat = DateFormatter() dateFormat.dateFormat = formatStr dateFormat.timeZone = zone let str = dateFormat.string(from: date) return str } }