Thursday, June 28, 2012

Get first day of a month.

First we will build first date (01-xx-xxxx)of a given month.
Of course you can change 01 to anything like 12,26 or whatever date you want to find day of.

int month = 4;
int year=2012;

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSDate *date=[dateFormatter dateFromString:[NSString stringWithFormat:@"01-%i-%i",month,year]];
[dateFormatter release];

Then we will find day for the above date in Gregorian Calendar. You can choose the method give in  previous article where you create NSDateFormatter with @"EEEE",But if you are calendar specific, then following is the way.

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:date];
int firstDay = [weekdayComponents weekday];//1 for Sun,2 for Mon etc
[gregorian release];

No comments:

Post a Comment