Get 1st day of the Current Quarter - xcode6

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.

Related

NSDate intervals for yesterday

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.

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];

number of calendarweeks for year (ISO 8601 definition)

how can I calculate the number of calendarweeks in objective-C for a given year.
I tried:
[calendar rangeOfUnit:NSWeekOfYearCalendarUnit inUnit: NSYearCalendarUnit forDate: [NSDate date]].length
but it returns 54.
Thanks
You are using NSWeekOfYearCalendarUnit, so you must use the corresponding larger unit which is NSYearForWeekOfYearCalendarUnit.
NSCalendar *calendar = [NSCalendar currentCalendar];
calendar.firstWeekday = 2;
calendar.minimumDaysInFirstWeek = 4;
int n = [calendar rangeOfUnit:NSWeekOfYearCalendarUnit inUnit:NSYearForWeekOfYearCalendarUnit forDate: [NSDate date]].length;
NSLog(#"%d", n); // 52
Finally, note that both NSWeekOfYearCalendarUnit and NSYearForWeekOfYearCalendarUnit are iOS 5.0 and OS X 10.7 only.
Edit
As noted by #lnafziger, if you use a date that is in a calendar week from the previous year or next year such as 1/1/2016, this will calculate the number of weeks in that year (2015 in the example), and not the actual year of the date (2016 in the example). If this is not what you want, you can change the date like follows:
NSDateComponents *components = [calendar components:NSYearCalendarUnit fromDate:date];
components.month = 3;
date = [calendar dateFromComponents:components];
After a significant amount of testing, here is a function which will return it for any year:
- (NSUInteger)iso8601WeeksForYear:(NSUInteger)year {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *firstThursdayOfYearComponents = [[NSDateComponents alloc] init];
[firstThursdayOfYearComponents setWeekday:5]; // Thursday
[firstThursdayOfYearComponents setWeekdayOrdinal:1]; // The first Thursday of the month
[firstThursdayOfYearComponents setMonth:1]; // January
[firstThursdayOfYearComponents setYear:year];
NSDate *firstThursday = [calendar dateFromComponents:firstThursdayOfYearComponents];
NSDateComponents *lastDayOfYearComponents = [[NSDateComponents alloc] init];
[lastDayOfYearComponents setDay:31];
[lastDayOfYearComponents setMonth:12];
[lastDayOfYearComponents setYear:year];
NSDate *lastDayOfYear = [calendar dateFromComponents:lastDayOfYearComponents];
NSDateComponents *result = [calendar components:NSWeekCalendarUnit fromDate:firstThursday toDate:lastDayOfYear options:0];
return result.week + 1;
}
Basically, per the spec, the total number of weeks is the same as the total number of Thursday's in the year, which is what this calculates.
I have tested it for the entire 400 year cycle (starting in the year 0 and the year 2000) and all cases match the spec.

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

How to know list of Mondays dates in a month using NSCalendar?

I would like to know the dates of all Monday's in a month using NSCalendar in Objective-C. So Please help me.
Thanks in advance
I blogged a solution for this a few months ago
http://brandontreb.com/case-of-the-mondays/
From https://discussions.apple.com/thread/1700102?start=0&tstart=0 and the Apple NSCalendar reference:
How about using something like this -
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:1965]; // Year of the calendar month
[comps setMonth:1]; // Month
[comps setDay:6]; // Any day
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];
Then, once you have the NSDate, do this:
NSDate * testDate = [NSDate date];
NSString * weekdayString = [testDate descriptionWithCalendarFormat:#"%A" timeZone:nil
locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];
NSLog(#"Day of the week: %#", weekdayString);
// weekdayString should look like "Monday", etc.
So, you can loop through the month's days until;
[weekdayString isEqualToString:#"Monday"] // or your desired day
And then just add 7 days to get the other 4 or so dates.
This may not be the prettiest solution, but it should work.