-(NSDate *)beginningOfDay:(NSDate *)date
{
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:date];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
return [cal dateFromComponents:components];
}
-(NSDate *)endOfDay:(NSDate *)date
{
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSMonthCalendarUnit | NSYearCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:date];
[components setHour:23];
[components setMinute:59];
[components setSecond:59];
return [cal dateFromComponents:components];
}
When I call : [self endOfDay:[NSDate date]]; I get the first of the month ... Why is that? I use this two methods because I need an interval that is from the first second of the first date (beginningOfDay:date1) to the last second of the second date (endOfDay:Date2) ...
For me none of the answers here and else where on stackoverflow worked. To get start of today i did this.
Note this
[gregorian setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
and[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
.When a calendar is created it gets initialised with current timezone and when date is extracted from its components, since NSDate has no timezone, the date from current timezone is considered as UTC timezone. So we need to set the timezone before extracting components and later when extracting date from these components.
Swift3 Using *XCode8
Apple is removing the
NS
from the class name so thatNSDate
can be swapped out toDate
. You may get a compiler warning if you try to cast them saying they will always fail, but they work fine when you run them in the playground.I replaced my generated
NSDate
in core data model withDate
and they still work.Since
iOS 8.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+
there is a built in function in the Foundation, which you can use out of the box. No need to implement own functions.public func startOfDay(for date: Date) -> Date
So you can use it this way:
let midnightDate = Calendar(identifier: .gregorian).startOfDay(for: Date())
It's worth to remember, that this takes upon consideration the device time zone. You can set
.timeZone
oncalendar
if you want to have eg UTC zone.Link to the Apple reference pages: https://developer.apple.com/reference/foundation/nscalendar/1417161-startofday.
You are missing
NSDayCalendarUnit
inSwift 4 Simple and more precise answer.
Start time: 00:00:00
End time: 23:59:59.5
Start Of Day / End Of Day — Swift 4