Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip time in NSDate?

I want to get difference between dates skipping time means if one date is 13 Jan 2012 - 11 pm and other date is 14 Jan 2012 - 12 am,then difference should be 1 day not 0 day.I mean I want difference between date only, 14 Jan 2012 - 13 Jan 2012, skipping time. I know I can use NSDate api to calculate difference but the problem is it consider time also.So I thought while calculating difference I will skip time but I do not know how to skip time because if I use NSDateFormatter it will return string not date.Please help me what I can do?

Thanks in advance!

like image 678
Nuzhat Zari Avatar asked Jan 13 '12 14:01

Nuzhat Zari


1 Answers

What you need to do is get the NSDateComponents of each date first. Once you do that you can compare the 'day' component to get you difference.

NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
[cal setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *date1 = ....;
NSDate *date2 = ....;
NSDateComponents *comps1 = [cal components:NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:date1];
NSDateComponents *comps2 = [cal components:NSDayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit fromDate:date2];

date1 = [cal dateFromComponents:comps1];
date2 = [cal dateFromComponents:comps2];

NSDateComponents *diffComps = [cal components:NSDayCalendarUnit fromDate:date1 toDate:date2 options:0];

NSLog(@"Days diff = %d", diffComps.day);

The date API can be kind of weird to wrap your head around, but once you do it is quite powerful.

like image 96
Joshua Weinberg Avatar answered Nov 15 '22 06:11

Joshua Weinberg