NSDate intervals for yesterday - objective-c

I need to filter search results based on values that were added yesterday. I have seen plenty on finding yesterday using:
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *components = [cal components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) fromDate:[[NSDate alloc] init]];
[components setHour:-24];
[components setMinute:0];
[components setSecond:0];
NSDate *yesterday = [cal dateByAddingComponents:components toDate:[NSDate date] options:0];
predicate = [NSPredicate predicateWithFormat:#"created_at >= %#", yesterday];
But this finds 24 hours since this exact moment in time. I need to filter yesterday as 12:01am-12:00pm. So the actual 24 hour period that was yesterday.
I'm guessing that I need to do something along the lines of:
1. Take the current date
2. Find the time from the current date to 12:01am of the same day
3. Then subtract 24 hours from that date
I feel confident I can do #3 (and #1 of course), but I'm not sure how to go about #2. I maybe over thinking it but I can't seem to grasp how to say: "Ok, it's 8:03am, I need to remove 8 hours and 2 minutes which will put me at 12:01am".

Start with some date of today, for example "now":
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *now = [NSDate date];
Subtract one day to get some date of yesterday:
NSDateComponents *minusOneDay = [[NSDateComponents alloc] init];
[oneDay setDay:-1];
NSDate *nowMinusOneDay = [cal dateByAddingComponents:minusOneDay toDate:now options:0];
Compute start and end date of the "day calendar unit" that contains yesterday's date:
NSDate *startOfYesterday;
NSTimeInterval lengthOfYesterday;
[cal rangeOfUnit:NSDayCalendarUnit startDate:&startOfYesterday interval:&lengthOfYesterday forDate:nowMinusOneDay];
NSDate *endOfYesterday = [startOfYesterday dateByAddingTimeInterval:lengthOfYesterday];
This should work even if a daylight savings time transition occurs between today and yesterday.
Generally one should avoid to use explicit time intervals such as "24 hours", because not every day has that length.

Related

Get 1st day of the Current Quarter

is there a way to get the first date of the current quarter of the year? I already know how to get the current Day of the week, month and year... i use this code:
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDateComponents* comps = [calendar components:
NSCalendarUnitYearForWeekOfYear |
NSCalendarUnitYear|
NSCalendarUnitMonth|
NSCalendarUnitWeekOfMonth|
NSCalendarUnitWeekday
fromDate:[NSDate date]];
[comps setWeekday:2]; // 2: monday
NSDate * firstDayOfTheWeek = [calendar dateFromComponents:comps];
[comps setWeekday:1]; // 1: Sunday
NSDate *lastDayOfTheWeek = [calendar dateFromComponents:comps];
[comps setDay:1];
NSDate * firstDayOfTheMonth = [calendar dateFromComponents:comps];
Humm... It seems that using:
[comps setMonth:1];
is a buyable option provided, I determine the current month to plot the quarter (and encapsulate it into a switch statement), guess this might be easier but, what about other countries that have different way of measuring the "Quarter". for my current requirement, this will have to do but if someone can give me a better way of getting the current date of the current quarter.

Number of Months and Days between two NSDates

I would like to calculate the number of months and days between two NSDates. I have the number of days calculating correctly, but how can convert that to months and remainder days?
This is what I'm using to calculate total number of days, which is working correctly.
- (NSInteger) numberOfDaysUntil {
NSDate *fromDate;
NSDate *toDate;
NSCalendar *calendar = [NSCalendar currentCalendar];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&fromDate interval:NULL forDate:[self dateOnly:[NSDate date]]];
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&toDate interval:NULL forDate:[self dateOnly:self]];
NSDateComponents *difference = [calendar components:NSDayCalendarUnit fromDate:fromDate toDate:toDate options:0];
return [difference day];
}
As Hot Licks correctly said, you can't convert a number of days to months/days in most calendars.
However, the NSCalendar method components:fromDate:toDate:options: can do this calculation if you agree with Apple's implementation. From the documentation:
The result is lossy if there is not a small enough unit requested to hold the full precision of the difference. Some operations can be ambiguous, and the behavior of the computation is calendar-specific, but generally larger components will be computed before smaller components; for example, in the Gregorian calendar a result might be 1 month and 5 days instead of, for example, 0 months and 35 days.
The discussion in the documentation even includes sample code for exactly your problem:
NSDate *startDate = ...;
NSDate *endDate = ...;
unsigned int unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *comps = [gregorian components:unitFlags fromDate:startDate toDate:endDate options:0];
int months = [comps month];
int days = [comps day];

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!
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.

Get date for every year july using NSDate

How to get date for every year of july month using NSDate .I am getting the data from the web service which I called. And now I am showing the full data in the graph which is very huge. The data which we are having is from 1998 to till now. so I want to show the data only every year of july. For this I need the help. Can anyone help me?
Well, NSDate is a specific date and time and not just month and year. If you're fine with something like every July 1 at 12 AM (or whatever time/day) then you can use NSDateComponents to set the components of the date.
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setMonth:5];
[comps setYear:2004];
NSCalendar *gregorian = [[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];
[gregorian release];
This is straight from the Apple documentation. If you want to get the next year, then you can use dateByAddingTimeInterval: on your NSDate to return a new date (or you can use the original NSDateComponents and setYear: in a loop).

Calculating the end of a month, or its last second

I have the simplest of tasks that I can't figure out how to do correctly. With the snippet below I can find out the beginning of a month.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *beginning = nil;
[cal rangeOfUnit:NSMonthCalendarUnit startDate:&beginning interval:NULL forDate:self];
return beginning;
Now I want to determine the end of that same month (the last second at 23:59:59 would suit my purposes). My first thought was to start at the first day of the next month and subtract a second. But I couldn't break down the date in an NSDateComponent instance to [dateComponents setMonth:[dateComponents month] + 1], because in the case of December that method wouldn't accept 12 + 1 = 13 to get to January, right?
Then how would I get to the last second of a month?
Do this to get the beginning of next month:
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setMonth:1];
NSDate *beginningOfNextMonth = [cal dateByAddingComponents:comps toDate:beginning options:0];
[comps release];
Alright, I think I have it. I'm using the rangeOfUnit:inUnit:forDate: method to determine the length of the current month in days, and add the corresponding NSTimeInterval to the month's start date.
- (NSDate *)firstSecondOfTheMonth {
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *beginning = nil;
if ([cal rangeOfUnit:NSMonthCalendarUnit startDate:&beginning interval:NULL forDate:self])
return beginning;
return nil;
}
- (NSDate *)lastSecondOfTheMonth {
NSDate *date = [self firstSecondOfTheMonth];
NSCalendar *cal = [NSCalendar currentCalendar];
NSRange month = [cal rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:date];
return [date dateByAddingTimeInterval:month.length * 24 * 60 * 60 - 1];
}
Note: Although this code works as I intended it to work, the answer that #spacehunt gave more clearly communicates the purpose.
The last second of the month... Most of the time, that boils down to taking the first second of the next month, and subtracting one second.
But are you asking the right question? What's the meaning of that last second? My guess is that you want to express a time interval starting from (and including) the first second of month N, and ending right before the first second of month N+1.