-
-
Save resand/d8f54ab0ec6db8129a650050edc655b5 to your computer and use it in GitHub Desktop.
Swift NSDate utils: Get date by adding / subtracting days from now, date at midnight, ...
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
| // | |
| // NSDate+Utils.swift | |
| // Swift Extensions | |
| // | |
| import Foundation | |
| import UIKit | |
| extension NSDate { | |
| class func dateByAddingDays(days: Int) -> NSDate { | |
| return self.days(days) | |
| } | |
| class func dateBySubstractingDays(days: Int) -> NSDate { | |
| return NSDate.days(-days) | |
| } | |
| } | |
| extension NSDate { | |
| class func days(days:Int) -> NSDate { | |
| return NSCalendar.currentCalendar().dateByAddingUnit( [.Day], value: days, toDate: NSDate(), options: [] )! | |
| } | |
| } | |
| extension NSDate { | |
| class func dateAtPrevMidnight() -> NSDate? { | |
| let date = NSDate.dateBySubstractingDays(1) | |
| let calendar = NSCalendar.currentCalendar() | |
| let components = calendar.components([.Year, .Month, .Day, .Hour, .Minute, .Second], fromDate: date) | |
| // Specify date components | |
| let dateComponents = NSDateComponents() | |
| dateComponents.year = components.year | |
| dateComponents.month = components.month | |
| dateComponents.day = components.day | |
| dateComponents.timeZone = NSTimeZone(name: "UTC") | |
| dateComponents.hour = 0 | |
| dateComponents.minute = 0 | |
| dateComponents.second = 0 | |
| // Create date from components | |
| let userCalendar = NSCalendar.currentCalendar() | |
| let dateTime = userCalendar.dateFromComponents(dateComponents) | |
| return dateTime | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment