Date+Extension.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  1. //
  2. // Date+Extension.swift
  3. // O2Platform
  4. //
  5. // Created by FancyLou on 2018/7/26.
  6. // Copyright © 2018 zoneland. All rights reserved.
  7. //
  8. import Foundation
  9. import CocoaLumberjack
  10. extension Date {
  11. func add(component: Calendar.Component, value: Int) -> Date {
  12. return Calendar.current.date(byAdding: component, value: value, to: self)!
  13. }
  14. var startOfDay: Date {
  15. return Calendar.current.startOfDay(for: self)
  16. }
  17. func getDateWithDay() -> Int {
  18. return NSCalendar.current.component(.day, from: self)
  19. }
  20. func getDateWithMonth() -> Int {
  21. return NSCalendar.current.component(.month, from: self)
  22. }
  23. func getDateWithYear() -> Int {
  24. return NSCalendar.current.component(.year, from: self)
  25. }
  26. /// 判断当前日期是否为今年
  27. // func isThisYear() -> Bool {
  28. // // 获取当前日历
  29. // let calender = Calendar.current
  30. // // 获取日期的年份
  31. // let yearComps = calender.component(.year, from: self)
  32. // // 获取现在的年份
  33. // let nowComps = calender.component(.year, from: Date())
  34. //
  35. // return yearComps == nowComps
  36. // }
  37. /// 是否是昨天
  38. // func isYesterday() -> Bool {
  39. // // 获取当前日历
  40. // let calender = Calendar.current
  41. // // 获取日期的年份
  42. // let comps = calender.dateComponents([.year, .month, .day], from: self, to: Date())
  43. // // 根据头条显示时间 ,我觉得可能有问题 如果comps.day == 0 显示相同,如果是 comps.day == 1 显示时间不同
  44. // // 但是 comps.day == 1 才是昨天 comps.day == 2 是前天
  45. // // return comps.year == 0 && comps.month == 0 && comps.day == 1
  46. // return comps.year == 0 && comps.month == 0 && comps.day == 0
  47. // }
  48. /// 是否是前天
  49. func isBeforeYesterday() -> Bool {
  50. // 获取当前日历
  51. let calender = Calendar.current
  52. // 获取日期的年份
  53. let comps = calender.dateComponents([.year, .month, .day], from: self, to: Date())
  54. //
  55. // return comps.year == 0 && comps.month == 0 && comps.day == 2
  56. return comps.year == 0 && comps.month == 0 && comps.day == 1
  57. }
  58. // 当前日期是否小于传入日期
  59. func isBefore(date: Date) -> Bool {
  60. return self.timeIntervalSince1970 < date.timeIntervalSince1970
  61. }
  62. /// 判断是否是今天
  63. // func isToday() -> Bool {
  64. // // 日期格式化
  65. // let formatter = DateFormatter()
  66. // // 设置日期格式
  67. // formatter.dateFormat = "yyyy-MM-dd"
  68. //
  69. // let dateStr = formatter.string(from: self)
  70. // let nowStr = formatter.string(from: Date())
  71. // return dateStr == nowStr
  72. // }
  73. }
  74. extension Date {
  75. /// String -> Date
  76. ///
  77. /// - Parameters:
  78. /// - dateStr: date string
  79. /// - formatter: date formatter
  80. /// - Returns: Date
  81. static func date(_ dateStr: String, formatter: String = "yyyy-MM-dd HH:mm:ss") -> Date? {
  82. let dateFormatter = DateFormatter()
  83. dateFormatter.dateFormat = formatter
  84. dateFormatter.locale = Locale.current
  85. return dateFormatter.date(from: dateStr)
  86. }
  87. /// Date -> String
  88. ///
  89. /// - Parameter formatter: date formatter
  90. /// - Returns: date string
  91. func toString(_ formatter: String) -> String {
  92. let dateFormatter = DateFormatter()
  93. dateFormatter.dateFormat = formatter
  94. dateFormatter.locale = Locale.current
  95. return dateFormatter.string(from: self)
  96. }
  97. }
  98. extension Date {
  99. static func currentCalendar() -> Calendar {
  100. var sharedCalendar = Calendar(identifier: .gregorian)
  101. sharedCalendar.locale = Locale.current
  102. return sharedCalendar
  103. }
  104. /// 获取当前 秒级 时间戳 - 10位
  105. var timeStamp : String {
  106. let timeInterval: TimeInterval = self.timeIntervalSince1970
  107. let timeStamp = Int(timeInterval)
  108. return "\(timeStamp)"
  109. }
  110. /// 获取当前 毫秒级 时间戳 - 13位
  111. var milliStamp : String {
  112. let timeInterval: TimeInterval = self.timeIntervalSince1970
  113. let millisecond = CLongLong(round(timeInterval*1000))
  114. return "\(millisecond)"
  115. }
  116. /// Example: 2000/1/2 03:04:05 return 2000
  117. var year: Int {
  118. get {
  119. return Date.currentCalendar().component(.year, from: self)
  120. }
  121. }
  122. /// Example: 2000/1/2 03:04:05 return 1
  123. var month: Int {
  124. get {
  125. return Date.currentCalendar().component(.month, from: self)
  126. }
  127. }
  128. /// Example: 2000/1/2 03:04:05 return 2
  129. var day: Int {
  130. get {
  131. return Date.currentCalendar().component(.day, from: self)
  132. }
  133. }
  134. /// Example: 2000/1/2 03:04:05 return 3
  135. var hour: Int {
  136. get {
  137. return Date.currentCalendar().component(.hour, from: self)
  138. }
  139. }
  140. /// Example: 2000/1/2 03:04:05 return 4
  141. var minute: Int {
  142. get {
  143. return Date.currentCalendar().component(.minute, from: self)
  144. }
  145. }
  146. /// Example: 2000/1/2 03:04:05 return 5
  147. var second: Int {
  148. get {
  149. return Date.currentCalendar().component(.second, from: self)
  150. }
  151. }
  152. /// 当前时间的月份的第一天是周几
  153. var firstWeekDayInThisMonth: Int {
  154. var calendar = Calendar.current
  155. let componentsSet = Set<Calendar.Component>([.year, .month, .day])
  156. var components = calendar.dateComponents(componentsSet, from: self)
  157. calendar.firstWeekday = 1
  158. components.day = 1
  159. let first = calendar.date(from: components)
  160. let firstWeekDay = calendar.ordinality(of: .weekday, in: .weekOfMonth, for: first!)
  161. return firstWeekDay! - 1
  162. }
  163. /// 当前时间的月份共有多少天
  164. var totalDaysInThisMonth: Int {
  165. let totalDays = Calendar.current.range(of: .day, in: .month, for: self)
  166. return (totalDays?.count)!
  167. }
  168. /// 上个月份的此刻日期时间
  169. var lastMonth: Date {
  170. var dateComponents = DateComponents()
  171. dateComponents.month = -1
  172. let newData = Calendar.current.date(byAdding: dateComponents, to: self)
  173. return newData!
  174. }
  175. /// 下个月份的此刻日期时间
  176. var nextMonth: Date {
  177. var dateComponents = DateComponents()
  178. dateComponents.month = +1
  179. let newData = Calendar.current.date(byAdding: dateComponents, to: self)
  180. return newData!
  181. }
  182. }
  183. extension Date {
  184. /// the same year
  185. ///
  186. /// - Parameter date: contrast time
  187. /// - Returns: true: equal; false: not equal
  188. func haveSameYear(_ date: Date) -> Bool {
  189. return self.year == date.year
  190. }
  191. /**间隔天数
  192. */
  193. func betweenDays(_ date: Date) -> Int {
  194. let components = Calendar.current.dateComponents([.day], from: self, to: date)
  195. return abs(components.day ?? 0)
  196. }
  197. func haveSameYearAndMonth(_ date: Date) -> Bool {
  198. return self.haveSameYear(date) && self.month == date.month
  199. }
  200. func haveSameYearMonthAndDay(_ date: Date) -> Bool {
  201. let components1 = Date.currentCalendar().dateComponents([.year, .month, .day], from: self)
  202. let components2 = Date.currentCalendar().dateComponents([.year, .month, .day], from: date)
  203. return components1 == components2
  204. }
  205. func haveSameYearMonthDayAndHour(_ date: Date) -> Bool {
  206. let components1 = Date.currentCalendar().dateComponents([.year, .month, .day, .hour], from: self)
  207. let components2 = Date.currentCalendar().dateComponents([.year, .month, .day, .hour], from: date)
  208. return components1 == components2
  209. }
  210. func haveSameYearMonthDayHourAndMinute(_ date: Date) -> Bool {
  211. let components1 = Date.currentCalendar().dateComponents([.year, .month, .day, .hour, .minute], from: self)
  212. let components2 = Date.currentCalendar().dateComponents([.year, .month, .day, .hour, .minute], from: date)
  213. return components1 == components2
  214. }
  215. func haveSameYearMonthDayHourMinuteAndSecond(_ date: Date) -> Bool {
  216. let components1 = Date.currentCalendar().dateComponents([.year, .month, .day, .hour, .minute, .second], from: self)
  217. let components2 = Date.currentCalendar().dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
  218. return components1 == components2
  219. }
  220. }
  221. extension Date {
  222. /// the number of days in the month
  223. ///
  224. /// - Returns: number of day
  225. func numberOfDaysInMonth() -> Int {
  226. if let range = Date.currentCalendar().range(of: .day, in: .month, for: self) {
  227. return range.count
  228. }
  229. return 0
  230. }
  231. /// 格式化时间
  232. ///
  233. /// - Parameters:
  234. /// - formatter: 格式 yyyy-MM-dd/YYYY-MM-dd/HH:mm:ss/yyyy-MM-dd HH:mm:ss
  235. /// - Returns: 格式化后的时间 String
  236. func formatterDate(formatter: String) -> String {
  237. let dateformatter = DateFormatter()
  238. dateformatter.dateFormat = formatter
  239. let dateString = dateformatter.string(from: self)
  240. return dateString
  241. }
  242. func friendlyTime() -> String {
  243. var returnTimeString = ""
  244. let now = Date()
  245. let millisecond = CLongLong(round(self.timeIntervalSince1970*1000))
  246. let nowMillisecond = CLongLong(round(now.timeIntervalSince1970*1000))
  247. let lt = millisecond / 86400000
  248. let ct = nowMillisecond / 86400000
  249. let days = Int(ct - lt);
  250. if (days == 0) {
  251. let hour = Int((nowMillisecond - millisecond) / 3600000)
  252. if (hour == 0) {
  253. let minuts = Int((nowMillisecond - millisecond) / 60000)
  254. if minuts > 1 {
  255. returnTimeString = "\(minuts)分钟前"
  256. }else {
  257. returnTimeString = "刚刚"
  258. }
  259. }else {
  260. returnTimeString = "\(hour)小时前"
  261. }
  262. }else if (days == 1) {
  263. returnTimeString = "昨天";
  264. } else if (days == 2) {
  265. returnTimeString = "前天 ";
  266. } else if (days > 2 && days < 31) {
  267. returnTimeString = "\(days)天前";
  268. } else if (days >= 31 && days <= 2 * 31) {
  269. returnTimeString = "一个月前";
  270. } else if (days > 2 * 31 && days <= 3 * 31) {
  271. returnTimeString = "2个月前";
  272. } else if (days > 3 * 31 && days <= 4 * 31) {
  273. returnTimeString = "3个月前";
  274. } else {
  275. returnTimeString = self.formatterDate(formatter: "yyyy-MM-dd")
  276. }
  277. return returnTimeString
  278. }
  279. }