Date+Extension.swift 10.0 KB

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