NSDate
extension that makes easier to operate with NSDate
, its built on the top functionalities of SWIFT to give the best experience and safety.
- Compare dates using common compare operators:
>, >=, <, <=
- Get interval between dates using that custom operator
>-<
- Add/remove date components by using aritmethic operators:
+, -, +=, -=
- Curryed functions
- Use subscripting to access single or group of date components
- iOS7 or above
- Swift 1.2
Embracing default values for parameters in SWIFT is possible to omit hour,minute and second arguments while creating a date, those will be set to 0.
let d1 = NSDate.dateWithTime(hour: 22)
let d2 = NSDate.dateWithTime(hour: 22, minutes:10)
let d3 = NSDate.dateWithComponents(year: 1978, month: 5, day: 24, hour: 12);
Using subsscript is possible to obtain only one component or group of componets in a touple of optionals (hour:Int?, minute:Int?, second:Int?, day:Int?, month:Int?, year:Int?)
. Values not requested are retuned as nil.
let d3 = NSDate.dateWithComponents(year: 1978, month: 5, day: 24, hour: 12);
let val = d3![.Months] // 5
let tupla = d3![.Hours,.Days,.Months] // (hour:12, nil, nil, day:24, month:5, nil)
println("Hour:\(tupla.hour!) Days:\(tupla.day!) Month:\(tupla.month!)")
Thanks to the Int extension is possible to add (or remove) seconds, minutes, hours days, weeks, months and years by simply those commands.
let date = NSDate()
let dateMinusOneDay = date - 1.days
let datePlustTwoHours = date + 2.hours
Compare dates using common compare operators: >, >=, <, <=
let now = NSDate()
let now2 = NSDate()
let answer = now == now2
println("\(answer)") // true
let laterDate = now2 + 1.days
let answer = laterDate! > now
println("\(answer)") // true
let earlierDate = now2 - 2.days
let answer2 = earlierDate! < now
println("\(answer2)") // true
You can easily use the provide curried functions dateByAddingCalendarComponent
and dateByRemovingCalendarComponent
to add an remove calendar units
let arrayDate = [NSDate(),NSDate.dateByAddingCalendarComponent(timeUnitMeasure: .Days)(date: NSDate(),value: 4)]
let addMonth = NSDate.dateByAddingCalendarComponent(timeUnitMeasure: .Months)
let mapArray = arrayDate.map{addMonth(date:$0!,value:3)}
Just copy AFDateSwiftExtension.swift
`file in your project.
Even if I was already working on that extension I must tell the article from Karatal blog has really inspired me
AFSwiftDateExtension
is released under MIT license. See LICENSE for details.