Checking the date of the same calendar day

Can someone please help me figure out how to check if the date is set on the same day as today. I think this will require creating a calendar day at 0 o’clock on the same day in the same time zone and checking for it, but so far my attempts have confused me the most.

+3
source share
2 answers

NSCalendar lets you do human days. So you can implement a category like this:

@implementation NSDate (IsItToday)
- (BOOL)isToday {
    NSUInteger desiredComponents = NSEraCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
    NSDateComponents *myCalendarDate = [[NSCalendar currentCalendar] components:desiredComponents fromDate:self];
    NSDateComponents *today = [[NSCalendar currentCalendar] components:desiredComponents fromDate:[NSDate date]];
    return [myCalendarDate isEqual:today];
}
@end
+5
source

You should read this Topic for dates and times well for Cocoa , but something like this should work:

NSDate *today = [NSDate date];
NSTimeInterval difference = [today timeIntervalSinceDate:otherDate];
NSTimeInterval secondsPerDay = 24 * 60 * 60;
if (difference < secondsPerDay)
{
   //same day as today
}
-1
source

Source: https://habr.com/ru/post/1710049/


All Articles