Friday, November 28, 2014

Extending NSDate to add a Start of Day Method

New NSDate objects are created by default with the current time and date. This is useful for most things. However sometimes you may only want the date. One way to achieve this is to modify the NSDate object's time elements using  the NSCalendar and NSDateComponent classes to set the time to the first second of the day. This article will describe how to do this by creating a Swift extension to the NSDate class that will add a 'start of day' method.



I will start by creating a new Swift file and adding the definition to extend the NSDate class.

extension NSDate {

}

Next I am going to add a new method called startOfDay which will return a new NSDate object.

    func startOfDay() -> NSDate {

    }

All NSDate objects include a time. The closest I can get to a date only NSDate is to set the time to the first second of the day. To do this I just need to set the hours, minutes and seconds to zero. This can be done by creating a calendar object and then using it to extract the date components from the original NSDate object.


    func startOfDay() -> NSDate {
        let calendar = NSCalendar.currentCalendar()

        var components = calendar.components(
.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear,
            fromDate: self)
    }

Next I need to make sure that the time components are zero.


        components.hour = 0
        components.minute = 0
        components.second = 0

Finally I will return a new NSDate object created by the NSCalendar class using the components I have modified.


extension NSDate {
    func startOfDay() -> NSDate {
        let calendar = NSCalendar.currentCalendar()

        var components = calendar.components(
.CalendarUnitDay | .CalendarUnitMonth | .CalendarUnitYear,
            fromDate: self)

        components.hour = 0
        components.minute = 0
        components.second = 0
        
        
        return calendar.dateFromComponents(components)!
    }
    

}

No comments:

Post a Comment