DateUtil.swift 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. //
  2. // DateUtils.swift
  3. // CommonUtil
  4. //
  5. // Created by lijunjie on 15/11/9.
  6. // Copyright © 2015年 lijunjie. All rights reserved.
  7. //
  8. import Foundation
  9. public class DateUtil {
  10. public let kNSDateHelperFormatFullDateWithTime = "MMM d, yyyy h:mm a"
  11. public let kNSDateHelperFormatFullDate = "MMM d, yyyy"
  12. public let kNSDateHelperFormatShortDateWithTime = "MMM d h:mm a"
  13. public let kNSDateHelperFormatShortDate = "MMM d"
  14. public let kNSDateHelperFormatWeekday = "EEEE"
  15. public let kNSDateHelperFormatWeekdayWithTime = "EEEE h:mm a"
  16. public let kNSDateHelperFormatTime = "h:mm a"
  17. public let kNSDateHelperFormatTimeWithPrefix = "'at' h:mm a"
  18. public let kNSDateHelperFormatSQLDate = "yyyy-MM-dd"
  19. public let kNSDateHelperFormatSQLTime = "HH:mm:ss"
  20. public let kNSDateHelperFormatSQLDateWithTime = "yyyy-MM-dd HH:mm:ss"
  21. static let share = DateUtil()
  22. private init () {}
  23. public func sharedCalendar() -> NSCalendar {
  24. var res = NSCalendar.current
  25. res.timeZone = NSTimeZone.system
  26. res.firstWeekday = 2
  27. return res as NSCalendar
  28. }
  29. public func sharedDateFormatter() -> DateFormatter {
  30. // struct Static {
  31. // static var onceToken: dispatch_once_t = 0
  32. // static var instance: DateFormatter? = nil
  33. // }
  34. // dispatch_once(&Static.onceToken) {
  35. // Static.instance = DateFormatter()
  36. // }
  37. // return Static.instance!
  38. return {DateFormatter()}()
  39. }
  40. public func detailTimeAgoString(date: NSDate) -> String {
  41. let timeNow = date.timeIntervalSince1970
  42. let calendar = self.sharedCalendar()
  43. let unitFlags = NSCalendar.Unit.month.rawValue | NSCalendar.Unit.day.rawValue | NSCalendar.Unit.year.rawValue | NSCalendar.Unit.hour.rawValue | NSCalendar.Unit.minute.rawValue | NSCalendar.Unit.second.rawValue | NSCalendar.Unit.weekOfYear.rawValue | NSCalendar.Unit.weekday.rawValue
  44. var component = calendar.components(NSCalendar.Unit(rawValue: unitFlags), from: date as Date)
  45. let year = component.year
  46. let month = component.month
  47. let day = component.day
  48. let today = NSDate()
  49. component = calendar.components(NSCalendar.Unit(rawValue: unitFlags), from: today as Date)
  50. let t_year = component.year
  51. var string: String
  52. let now = today.timeIntervalSince1970
  53. let distance = now - timeNow
  54. if distance < 60 {
  55. string = "刚刚"
  56. } else if distance < 60*60 {
  57. string = String(format: "%lld分钟前", distance/60)
  58. } else if distance < 60*60*24 {
  59. string = String(format: "%lld小时前", distance/60/60)
  60. } else if distance < 60*60*24*7 {
  61. string = String(format: "%lld天前", distance/60/60/24)
  62. } else if year == t_year {
  63. string = String(format: "%ld月%ld日", month!, day!)
  64. } else {
  65. string = String(format: "%ld年%ld月%ld日", year!, month!, day!)
  66. }
  67. return string
  68. }
  69. public func detailTimeAgoStringByInterval(timeInterval: TimeInterval) -> String {
  70. return self.detailTimeAgoString(date: self.dateFromTimeInterval(timeInterval: timeInterval))
  71. }
  72. public func daysAgoFromNow(date: NSDate) -> Int {
  73. let calendar = self.sharedCalendar()
  74. let components = calendar.components(NSCalendar.Unit.day, from: date as Date, to: NSDate() as Date, options: NSCalendar.Options(rawValue: 0))
  75. return components.day!
  76. }
  77. public func daysAgoAgainstMidnight(date: NSDate) -> Int {
  78. let mdf = self.sharedDateFormatter()
  79. mdf.dateFormat = kNSDateHelperFormatSQLDate
  80. let midnight = mdf.date(from: mdf.string(from: date as Date))
  81. return Int((midnight?.timeIntervalSinceNow)! / (-60 * 60 * 24))
  82. }
  83. public func stringDaysAgoAgainstMidnight(flag: Bool, withDate date:NSDate ) -> String {
  84. let daysAgo: Int = flag ? self.daysAgoAgainstMidnight(date: date) : self.daysAgoFromNow(date: date)
  85. var text: String
  86. switch daysAgo {
  87. case 0:
  88. text = "今天"
  89. case 1:
  90. text = "昨天"
  91. default:
  92. text = String(format: "%lu天前", daysAgo)
  93. }
  94. return text
  95. }
  96. public func stringDaysAgo(date:NSDate) -> String {
  97. return self.stringDaysAgoAgainstMidnight(flag: true, withDate: date)
  98. }
  99. /*
  100. * iOS中规定的就是周日为1,周一为2,周二为3,周三为4,周四为5,周五为6,周六为7,
  101. * 无法通过某个设置改变这个事实的,只能在使用的时候注意一下这个规则了。
  102. */
  103. public func weekDay(date: NSDate) -> Int {
  104. let weekdayComponents = self.sharedCalendar().components(NSCalendar.Unit.weekday, from: date as Date)
  105. var wDay = weekdayComponents.weekday!
  106. if wDay == 1 {
  107. wDay = 7
  108. } else {
  109. wDay -= 1
  110. }
  111. return wDay
  112. }
  113. public func weekDayString(date: NSDate) -> String {
  114. let weekNameDict = [
  115. 1 : "一",
  116. 2 : "二",
  117. 3 : "三",
  118. 4 : "四",
  119. 5 : "五",
  120. 6 : "六",
  121. 7 : "日"
  122. ]
  123. let weekName = weekNameDict[self.weekDay(date: date)]
  124. return String(format: "星期%@", weekName!)
  125. }
  126. public func weekNumberString(date: NSDate) -> String {
  127. return String(format: "第%lu周", self.weekNumber(date: date))
  128. }
  129. public func weekNumber(date: NSDate) -> Int {
  130. let calendar = self.sharedCalendar()
  131. let dateComponents = calendar.components(NSCalendar.Unit.weekOfYear, from: date as Date)
  132. return dateComponents.weekOfYear!
  133. }
  134. public func hour(date: NSDate) -> Int {
  135. let calendar = self.sharedCalendar()
  136. let dateComponents = calendar.components(NSCalendar.Unit.hour, from: date as Date)
  137. return dateComponents.hour!
  138. }
  139. public func minute(date: NSDate) -> Int {
  140. let calendar = self.sharedCalendar()
  141. let dateComponents = calendar.components(NSCalendar.Unit.minute, from: date as Date)
  142. return dateComponents.minute!
  143. }
  144. public func year(date: NSDate) -> Int {
  145. let calendar = self.sharedCalendar()
  146. let dateComponents = calendar.components(NSCalendar.Unit.year, from: date as Date)
  147. return dateComponents.year!
  148. }
  149. public func month(date: NSDate) -> Int {
  150. let calendar = self.sharedCalendar()
  151. let dateComponents = calendar.components(NSCalendar.Unit.month, from: date as Date)
  152. return dateComponents.month!
  153. }
  154. public func day(date: NSDate) -> Int {
  155. let calendar = self.sharedCalendar()
  156. let dateComponents = calendar.components(NSCalendar.Unit.day, from: date as Date)
  157. return dateComponents.day!
  158. }
  159. public func dateFromTimeInterval(timeInterval: TimeInterval) -> NSDate {
  160. return NSDate(timeIntervalSince1970: timeInterval)
  161. }
  162. public func dateFromString(string: String) -> NSDate {
  163. return self.dateFromString(string: string, withFormat: kNSDateHelperFormatSQLDate)
  164. }
  165. public func dateTimeFromString(string: String) -> NSDate {
  166. return self.dateFromString(string: string, withFormat:kNSDateHelperFormatSQLDateWithTime)
  167. }
  168. public func dateFromString(string: String, withFormat format: String) -> NSDate {
  169. let formatter = self.sharedDateFormatter()
  170. formatter.dateFormat = format
  171. return formatter.date(from: string)! as NSDate
  172. }
  173. public func stringFromDate(date: NSDate, withFormat format: String) -> String {
  174. let formatter = self.sharedDateFormatter()
  175. formatter.dateFormat = format
  176. return self.sharedDateFormatter().string(from: date as Date)
  177. }
  178. public func stringFromDate(date: NSDate) -> String {
  179. return self.stringFromDate(date: date, withFormat: kNSDateHelperFormatSQLDateWithTime)
  180. }
  181. public func stringWithDateStyle(dateStyle: DateFormatter.Style, timeStyle: DateFormatter.Style, withDate date: NSDate) -> String {
  182. let formatter = self.sharedDateFormatter()
  183. formatter.dateStyle = dateStyle
  184. formatter.timeStyle = timeStyle
  185. return formatter.string(from: date as Date)
  186. }
  187. public func beginningOfWeek(date: NSDate) -> NSDate {
  188. let calendar = self.sharedCalendar()
  189. var beginningOfWeek: NSDate? = nil
  190. let ok = calendar.range(of: NSCalendar.Unit.weekOfYear, start: &beginningOfWeek, interval: nil, for: date as Date)
  191. if ok {
  192. return beginningOfWeek!
  193. }
  194. let weekdayComponents = calendar.components(NSCalendar.Unit.weekday, from: date as Date)
  195. let componentsToSubtract = NSDateComponents()
  196. componentsToSubtract.day = -(weekdayComponents.weekday! - 1)
  197. beginningOfWeek = nil
  198. beginningOfWeek = calendar.date(byAdding: componentsToSubtract as DateComponents, to: date as Date, options: NSCalendar.Options(rawValue: 0)) as NSDate?
  199. let components = calendar.components(NSCalendar.Unit(rawValue: NSCalendar.Unit.year.rawValue | NSCalendar.Unit.month.rawValue | NSCalendar.Unit.day.rawValue), from: beginningOfWeek! as Date)
  200. return calendar.date(from: components)! as NSDate
  201. }
  202. public func beginningOfDay(date: NSDate) -> NSDate {
  203. let calendar = self.sharedCalendar()
  204. let components = calendar.components(NSCalendar.Unit(rawValue: NSCalendar.Unit.year.rawValue | NSCalendar.Unit.month.rawValue | NSCalendar.Unit.day.rawValue), from: date as Date)
  205. return calendar.date(from: components)! as NSDate
  206. }
  207. public func endOfWeek(date: NSDate) -> NSDate {
  208. let calendar = self.sharedCalendar()
  209. let weekdayComponents = calendar.components(NSCalendar.Unit(rawValue: NSCalendar.Unit.weekday.rawValue), from: date as Date)
  210. let componentsToAdd = NSDateComponents()
  211. componentsToAdd.day = 7 - weekdayComponents.weekday!
  212. return calendar.date(byAdding: componentsToAdd as DateComponents, to: date as Date, options: NSCalendar.Options(rawValue: 0))! as NSDate
  213. }
  214. public func dateFormatString() -> String {
  215. return kNSDateHelperFormatSQLDate
  216. }
  217. //
  218. // + (NSString *)dateFormatString
  219. // {
  220. // return kNSDateHelperFormatSQLDate
  221. // }
  222. //
  223. // + (NSString *)timeFormatString
  224. // {
  225. // return kNSDateHelperFormatSQLTime
  226. // }
  227. //
  228. // + (NSString *)timestampFormatString
  229. // {
  230. // return kNSDateHelperFormatSQLDateWithTime
  231. // }
  232. //
  233. // + (NSString *)dbFormatString
  234. // {
  235. // return kNSDateHelperFormatSQLDateWithTime
  236. // }
  237. public func birthdayToAge(date: NSDate) -> String {
  238. let calendar = self.sharedCalendar()
  239. let components = calendar.components(NSCalendar.Unit(rawValue: NSCalendar.Unit.year.rawValue | NSCalendar.Unit.month.rawValue | NSCalendar.Unit.day.rawValue), from: date as Date, to: NSDate() as Date, options:NSCalendar.Options(rawValue: 0))
  240. if components.year! > 0 {
  241. return String(format:"%ld岁", components.year!)
  242. } else if components.month! > 0 {
  243. return String(format:"%ld个月%ld天" , components.month!, components.day!)
  244. } else {
  245. return String(format: "%ld天", components.day!)
  246. }
  247. }
  248. public func birthdayToAgeByTimeInterval(date: TimeInterval) -> String {
  249. return self.birthdayToAge(date: self.dateFromTimeInterval(timeInterval: date))
  250. }
  251. public func dateToConstellation(date: NSDate) -> String? {
  252. let day = self.day(date: date)
  253. let month = self.month(date: date)
  254. if day == NSNotFound || month == NSNotFound {
  255. return nil
  256. }
  257. let constellations = [
  258. "水瓶座", "双鱼座", "白羊座", "金牛座", "双子座", "巨蟹座",
  259. "狮子座", "处女座", "天秤座", "天蝎座", "射手座", "摩羯座"
  260. ]
  261. var res: String? = nil
  262. if day <= 22 {
  263. if month != 1 {
  264. res = constellations[month - 2]
  265. } else {
  266. res = constellations[11]
  267. }
  268. } else {
  269. res = constellations[month - 1]
  270. }
  271. return res
  272. }
  273. public func dateToConstellationByTimeInterval(date: TimeInterval) -> String {
  274. return self.dateToConstellation(date: self.dateFromTimeInterval(timeInterval: date))!
  275. }
  276. // 月份开始日期
  277. public func monthStartDate(date: Date) -> Date {
  278. let calendar = Calendar.current
  279. let components = calendar.dateComponents(
  280. Set<Calendar.Component>([.year, .month]), from: date)
  281. let startOfMonth = calendar.date(from: components)!
  282. return startOfMonth
  283. }
  284. //月份最后日期 startDate是月份开始日期
  285. //returnEndTime 最后的时间是 true 23:59:59 false 00:00:00
  286. public func monthEndDate(startDate: Date, returnEndTime:Bool = true) -> Date {
  287. let calendar = Calendar.current
  288. var components = DateComponents()
  289. components.month = 1
  290. if returnEndTime {
  291. components.second = -1
  292. } else {
  293. components.day = -1
  294. }
  295. let endOfMonth = calendar.date(byAdding: components, to: startDate)!
  296. return endOfMonth
  297. }
  298. public func getMonthEnd(date: NSDate) -> NSDate {
  299. let format = DateFormatter.init()
  300. format.dateFormat = "yyyy-MM"
  301. let newDate: Date = format.date(from: format.string(from: date as Date))!
  302. var interval: Double = 0
  303. var beginDate: Date = Date()
  304. var endDate: Date = Date()
  305. var calendar = NSCalendar.current
  306. calendar.firstWeekday = 2 //设定周一为周首日
  307. let ok: Bool = calendar.dateInterval(of: .month, start: &beginDate, interval: &interval, for: newDate)
  308. //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
  309. if (ok) {
  310. endDate = beginDate.addingTimeInterval(interval - 1)
  311. }else {
  312. return Date.init() as NSDate;
  313. }
  314. let myDateFormatter = DateFormatter.init()
  315. myDateFormatter.dateFormat = "yyyy-MM-dd"
  316. endDate = myDateFormatter.date(from: myDateFormatter.string(from: endDate))!
  317. return endDate as NSDate;
  318. }
  319. public func getMonthBegin(date: NSDate) -> NSDate {
  320. let format = DateFormatter.init()
  321. format.dateFormat = "yyyy-MM"
  322. let newDate: Date = format.date(from: format.string(from: date as Date))!
  323. var interval: Double = 0
  324. var beginDate: Date = Date()
  325. var endDate: Date = Date()
  326. var calendar = NSCalendar.current
  327. calendar.firstWeekday = 2 //设定周一为周首日
  328. let ok: Bool = calendar.dateInterval(of: .month, start: &beginDate, interval: &interval, for: newDate)
  329. //分别修改为 NSDayCalendarUnit NSWeekCalendarUnit NSYearCalendarUnit
  330. if (ok) {
  331. endDate = beginDate.addingTimeInterval(interval - 1)
  332. }else {
  333. return Date.init() as NSDate;
  334. }
  335. let myDateFormatter = DateFormatter.init()
  336. myDateFormatter.dateFormat = "yyyy-MM-dd"
  337. endDate = Date.init(timeInterval: -86400, since: beginDate)
  338. return endDate as NSDate;
  339. }
  340. public func compareDate(oneDay: NSDate, anotherDay: NSDate) -> Int{
  341. let dateFormatter = DateFormatter.init()
  342. dateFormatter.dateFormat = "yyyy-MM"
  343. let dateA = dateFormatter.date(from: dateFormatter.string(from: oneDay as Date))
  344. let dateB = dateFormatter.date(from: dateFormatter.string(from: anotherDay as Date))
  345. let result = dateA?.compare(dateB!)
  346. if (result!.rawValue == ComparisonResult.orderedDescending.rawValue) {
  347. //NSLog(@"Date1 is in the future");
  348. return 1;
  349. }
  350. else if (result!.rawValue == ComparisonResult.orderedAscending.rawValue){
  351. //NSLog(@"Date1 is in the past");
  352. return -1;
  353. }
  354. //NSLog(@"Both dates are the same");
  355. return 0;
  356. }
  357. }
  358. public let SharedDateUtil: DateUtil = DateUtil.share