Tutorial :Compare NSDate objects only in terms of year month day

Question:

If I want to use the compare method to compare two days:

``[day1 compare:day2] == NSOrderedAscending  ``

How to compare only by year-month-day?

Solution:1

There are 86400 seconds in a day, so if you get the number of seconds since a reference date for both dates, you can divide them by 86400 and compare the two numbers.

This will give you (in `days1` and `days2`) the number of days for the dates that have passed since January 1st, 1970. You can then compare them.

``int days1 = [date1 timeIntervalSince1970] / 86400;  int days2 = [date2 timeIntervalSince1970] / 86400;  ``

Solution:2

Ideally, you would like to write something like:

``if ([date1 isSameDayAs:date2]) {...}  ``

You can achieve this with a simple category on NSDate, sonething like:

``@implementation NSDate (Extensions)  - (BOOL) isSameDayAs:(NSDate *)date2  {      int days1 = [self  timeIntervalSince1970] / 86400;      int days2 = [date2 timeIntervalSince1970] / 86400;      return (days1 == days2);  }  @end  ``

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »