1

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.

4

2 回答 2

2

代替

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

NSDateComponents *dateComponants = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate: date];
于 2013-06-07T09:51:23.757 回答
0

我是最高级的白痴!!!!

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

应该

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

看了一个小时...

于 2013-06-07T09:51:33.007 回答