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)
}
components.hour = 0
components.minute = 0
components.second = 0
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