Get first day in a month from NSCalendar

前端 未结 6 1416
醉话见心
醉话见心 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:38

    Your logic is wrong: Instead of setting the date's day to 1, you're adding a day to the current date.

    Try something like that:

    NSDate *today = [NSDate date];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    NSDateComponents *components = [gregorian components:(NSEraCalendarUnit | NSYearCalendarUnit | NSMonthCalendarUnit) fromDate:today];
    components.day = 1;
    
    NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];
    

提交回复
热议问题