Get first day in a month from NSCalendar

前端 未结 6 1317
醉话见心
醉话见心 2021-01-12 05:24

I have this subset of a method that needs to get day one of the current month.

NSDate *today = [NSDate date];  // returns correctly 28 february 2013
NSCalend         


        
6条回答
  •  北恋
    北恋 (楼主)
    2021-01-12 05:30

    Easy Way to get first and last date of previous month is :

    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comp = [gregorian components:(NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay ) fromDate:[NSDate date]];
    
    //TO GET PREVIOUS MONTH LAST DAY
    [comp setMonth:[comp month]];
    [comp setDay:1];
    NSDate *tDateMonth = [gregorian dateFromComponents:comp];
    NSLog(@"LAST DAY OF PREVIOUS MONTH ;  %@", tDateMonth);
    
    //TO GET PREVIOUS MONTH FIRST DAY
    [comp setMonth:[comp month]-1];
    [comp setDay:3];
    NSDate *td = [gregorian dateFromComponents:comp];
    NSLog(@"FIRST DAY OF PREVIOUS MONTH ;  %@", td);
    

    Hope this helps

提交回复
热议问题