Advertisement
SEEEEEAAAAAA10000000

Date + Strideable (Draft)

Jul 23rd, 2019
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 1.51 KB | None | 0 0
  1. import Foundation
  2.  
  3. let calendar = createCalendar()
  4.  
  5. func createCalendar() -> Calendar {
  6.     var cal = Calendar(identifier: .gregorian)
  7.     cal.timeZone = TimeZone(abbreviation: "UTC")!
  8.     return cal
  9. }
  10.  
  11. extension Date: Strideable {
  12.    
  13.     public typealias Stride = Int
  14.    
  15.     public func distance(to other: Date) -> Int {
  16.         let currentmask = calendar.startOfDay(for: self)
  17.         let targetmask = calendar.startOfDay(for: other)
  18.        
  19.         var result = 0
  20.         var curent = currentmask
  21.        
  22.         if self < other {
  23.             while curent < targetmask {
  24.                 curent = calendar.date(byAdding: .day, value: 1, to: curent)!
  25.                 result += 1
  26.             }
  27.         } else {
  28.             while curent > targetmask {
  29.                 curent = calendar.date(byAdding: .day, value: -1, to: curent)!
  30.                 result -= 1
  31.             }
  32.         }
  33.        
  34.        
  35.         return result
  36.     }
  37.    
  38.     public func advanced(by n: Int) -> Date {
  39.         let currentmask = calendar.startOfDay(for: self)
  40.         var index = 0
  41.         var current = currentmask
  42.        
  43.         if n > 0 {
  44.             while index < n {
  45.                 current = calendar.date(byAdding: .day, value: 1, to: current)!
  46.                 index += 1
  47.             }
  48.         } else {
  49.             while index > n {
  50.                 current = calendar.date(byAdding: .day, value: -1, to: current)!
  51.                 index -= 1
  52.             }
  53.         }
  54.        
  55.         return current
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement