Last active
February 13, 2016 23:30
-
-
Save fareskalaboud/68b7a85df527b1f0b4c9 to your computer and use it in GitHub Desktop.
If you work with a lot of dates and times in your apps, here’s a cool extension I wrote that allows you to quickly add hours, days, weeks or months to any date.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License. | |
// Created by Fares K. Alaboud on 13/01/2016. | |
// faresalaboud.me | |
import UIKit | |
extension NSDate { | |
func addToDate(measurement: DateComponent, number: Int) -> NSDate { | |
let dateComponents = NSDateComponents() | |
let CurrentCalendar = NSCalendar.currentCalendar() | |
let CalendarOption = NSCalendarOptions() | |
switch(measurement) { | |
case DateComponent.Hour: | |
dateComponents.hour = number | |
break | |
case DateComponent.Day: | |
dateComponents.day = number | |
break | |
case DateComponent.Week: | |
dateComponents.day = (number * 7) | |
break | |
case DateComponent.Month: | |
dateComponents.month = number | |
break | |
} | |
let newDate = CurrentCalendar.dateByAddingComponents(dateComponents, toDate: NSDate(), options: CalendarOption) | |
return newDate! | |
} | |
} | |
enum DateComponent { | |
case Hour | |
case Day | |
case Week | |
case Month | |
} | |
// Example: | |
// var now = NSDate() | |
// var tomorrow = now.addToDate(DateComponent.Day, number: 1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you for this. Really helpful :)