-(NSDate *)beginningOfDay:(NSDate *)date
{
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSMonthCalend
Swift 3
class func today() -> NSDate {
return NSDate()
}
class func dayStart() -> NSDate {
return NSCalendar.current.startOfDay(for: NSDate() as Date) as NSDate
}
class func dayEnd() -> NSDate {
let components = NSDateComponents()
components.day = 1
components.second = -1
return NSCalendar.current.date(byAdding: components as DateComponents, to: self.dayStart() as Date)
}
Just for reference, simple way to set Start and End of the day in Swift 4,
var comp: DateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())
comp.hour = 0
comp.minute = 0
comp.second = 0
comp.timeZone = TimeZone(abbreviation: "UTC")!
//Set Start of Day
let startDate : Date = Calendar.current.date(from: comp)!
print(“Day of Start : \(startDate)")
//Set End of Day
comp.hour = 23
comp.minute = 59
comp.second = 59
let endDate : Date = Calendar.current.date(from:comp)!
print("Day of End : \(endDate)")
You are missing NSDayCalendarUnit
in the components.
In iOS 8+ this is really convenient; you can do:
let startOfDay = NSCalendar.currentCalendar().startOfDayForDate(date)
To get the end of day then just use the NSCalendar methods for 23 hours, 59 mins, 59 seconds, depending on how you define end of day.
// Swift 2.0
let components = NSDateComponents()
components.hour = 23
components.minute = 59
components.second = 59
let endOfDay = NSCalendar.currentCalendar().dateByAddingComponents(components, toDate: startOfDay, options: NSCalendarOptions(rawValue: 0))
Date Math
Apple iOS NSCalendar Documentation. (See Section: Calendrical Calculations)
NSCalendar methods discussed by NSHipster.
Just another way using dateInterval(of:start:interval:for:)
of Calendar
and the dedicated DateInterval struct
On return startDate
contains the start of the day and interval
the number of seconds in the day.
func dateInterval(of date : Date) -> DateInterval {
var startDate = Date()
var interval : TimeInterval = 0.0
Calendar.current.dateInterval(of: .day, start: &startDate, interval: &interval, for: date)
return DateInterval(start: startDate, duration: interval-1)
}
let interval = dateInterval(of: Date())
print(interval.start, interval.end)
You don't have to set up the components to zero, just ignore them:
-(NSDate *)beginningOfDay:(NSDate *)date
{
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:date];
return [calendar dateFromComponents:components];
}