Get firstdate, lastdate of month?

后端 未结 8 1027
不思量自难忘°
不思量自难忘° 2021-02-01 21:29

I want to get firstdate、lastdate of month,I try

NSDateComponents *components = [calendar components:units fromDate:[NSDate date]];
[components setDay:1];
self.c         


        
8条回答
  •  难免孤独
    2021-02-01 22:17

    Looks like there is no need for any tricks or hacks, NSCalendar's rangeOfUnit does the job pretty nicely:

    NSCalendar *cal = [NSCalendar currentCalendar];
    
    NSDateComponents *dc = [[NSDateComponents alloc] init];
    dc.year = 1947;
    dc.month = 8; //desired month
    
    //calculate start date
    dc.day = 1; //As far as I can think start date of a month will always be 1
    NSDate *start = [cal dateFromComponents:dc];
    
    //calculate last date of month
    NSRange dim = [cal rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:start]; // we used start date as it has the same month & year value as desired
    dc.day=dim.length; //this is the simply the last day of the desired month
    NSDate *last = [[NSCalendar currentCalendar] dateFromComponents:dc];
    

    Log the values for verification:

    NSLog(@"Start day of month Date: %@", start);
    NSLog(@"Last day of month Date: %@", last);
    

    Apple docs on NSCalendar rangeOfUnit: https://developer.apple.com/documentation/foundation/nscalendar/1418344-rangeofunit

    p.s looks like this uses the same logic as @Scott Means's answer, but doesn't require any category, so use which ever answer you prefer!

提交回复
热议问题