Question

I have an NSDate and I want to find out the Week Day Name for the FIRST of the month from that NSDate. So for example I get given "15th of May 2013" and I want to return "Wednesday" as "1st of May 2013" was a Wednesday. Here is my test code;

    // Setup a Date and Formatter and load with a date
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];

    NSDate *date = [dateFormatter dateFromString:@"2013-05-10"];
    NSLog(@"Day In Month : %@", [dateFormatter stringFromDate:date]);

    // Setup a calendar and extract components and force to the first
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    //NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *dateComponants = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];

    [dateComponants setDay:1];

    date = [calendar dateFromComponents:dateComponants];
    NSLog(@"First Day : %@", [dateFormatter stringFromDate:date]);

    // Change the formatter for the Day name
    [dateFormatter setDateFormat:@"EEEE"];
    NSLog(@"Day Name : %@", [dateFormatter stringFromDate:date]);

And here is what my log says....

Day In Month : 2013-05-10
First Day : 2013-06-01
Day Name : Saturday

What is the June date doing in the middle? In fact the 1st of June is a Saturday but that does not really help me.

Thanks for any help.

Was it helpful?

Solution

Replace

NSDateComponents *dateComponants = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];

with

NSDateComponents *dateComponants = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate: date];

OTHER TIPS

I am an idiot of the highest degree!!!!

    NSDateComponents *dateComponants = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];

Should be

    NSDateComponents *dateComponants = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];

Been looking at it for an hour...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top