Question

I have a timestamp (NSDate) and I want to validate if another timestamp happened in the same calendar week, month, year, day, etc.

I tried to do this by defining 2 other NSDates, one as start date and one as end date. And then representing the desired timespan with these two dates.

Example for defining the start of the current day:

NSDate *myDate = [[NSDate alloc] init];
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:(
                                                NSEraCalendarUnit |
                                                NSMonthCalendarUnit |
                                                NSYearCalendarUnit |
                                                NSDayCalendarUnit |
                                                NSHourCalendarUnit |
                                                NSMinuteCalendarUnit |
                                                NSSecondCalendarUnit |
                                                NSTimeZoneCalendarUnit
                                                ) fromDate:myDate];

[components setHour:1];
[components setMinute:0];
[components setSecond:0];
startDate = [cal dateFromComponents:components];

This should set startDate to the time 00:00:00 on the current date. The problem is that this only works if myDate has current timezone. E.g. if we have winter time now, and NSDate is summer time it sets the time 1 hour wrong.

How can I consider the summer/winter time in this calculation, or is there a better way to represent a concrete timespan a calendar based timespan a timestamp lies in?

Was it helpful?

Solution

The easiest way to get a day/week/month/... timespan for a given date is the rangeOfUnit method. For example:

NSDate *date1, *date2;

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *startOfTimespan;
NSTimeInterval lengthOfTimespan;
[calendar rangeOfUnit:NSWeekOfYearCalendarUnit
        startDate:&startOfTimespan
         interval:&lengthOfTimespan
          forDate:date1];

Now startOfTimespan is the start of the week that contains date1, and lengthOfTimespan is the length of that week. So you can test date2 with

NSTimeInterval diff = [date2 timeIntervalSinceDate:startOfTimespan];
if ( diff >= 0 && diff < lengthOfTimespan) {
    // date1 and date2 are in the same week
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top