Get first day in a month from NSCalendar

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

    0 讨论(0)
  • 2021-01-12 05:37

    Easy way of getting to the 1st from a given date:

    NSDate *first = [gregorian dateBySettingUnit:NSCalendarUnitDay value:1 ofDate:date options:0]; 
    
    0 讨论(0)
  • 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];
    
    0 讨论(0)
  • 2021-01-12 05:38
    NSDate *startDate = nil;
    [[NSCalendar currentCalendar] rangeOfUnit:NSCalendarUnitMonth startDate:&startDate interval:NULL forDate:date];
    
    return startDate;
    
    0 讨论(0)
  • 2021-01-12 05:42

    By creating new variable is expensive on memory usage, it's better using date formatter to get the first day of the current month

    today = [NSDate date];
    
    firstDayDateFormatter = [[NSDateFormatter alloc] init];
    [firstDayDateFormatter setDateFormat:@"01-MM-yyyy"];
    dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:@"en_US"]];
    firstDayOfTheMonth = [mdfDateFormat dateFromString:[firstDayDateFormatter stringFromDate:today]];
    
    0 讨论(0)
  • 2021-01-12 05:56

    You want [NSCalender dateFromComponents:] instead:

    NSDate *dayOneInCurrentMonth = [gregorian dateFromComponents:components];
    
    0 讨论(0)
提交回复
热议问题