NSCalendar NSDateComponents weekofYear return 1 with date 2014-12-31

后端 未结 3 551
难免孤独
难免孤独 2021-01-28 17:01

I want to get weekofYear with date \'2014-12-31\' ,but it always return 1 not 52 here is my code:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSUIntege         


        
相关标签:
3条回答
  • 2021-01-28 17:44

    Set the minimumDaysInFirstWeek property of the NSCalendar instance before obtaining the date components.

    NSCalendar *calendar = [NSCalendar currentCalendar];
    calendar.minimumDaysInFirstWeek = 7; // the week has to be completely within one year
    
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
    
    NSLog(@"%i",dateComponent.weekOfYear); // 52
    
    0 讨论(0)
  • 2021-01-28 17:51

    An alternative approach is to use the yearForWeekOfYear property of the NSDateComponents instance. If the yearForWeekOfYear is after the year of the date passed to components:fromDate:, then it is week 52.

    E.g.

    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    NSUInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekOfMonthCalendarUnit | NSWeekOfYearCalendarUnit | NSYearForWeekOfYearCalendarUnit;
    NSDateComponents *dateComponent = [calendar components:unitFlags fromDate:[NSDate date]];
    
    NSInteger weekOfYear = dateComponent.weekOfYear;
    if (dateComponent.yearForWeekOfYear > dateComponent.year)
        weekOfYear = 52;
    NSLog(@"%i",weekOfYear); // 52
    
    0 讨论(0)
  • 2021-01-28 18:00

    IF the week is 1 (first days of 2015 or last few days of 2014)

    AND the day is greater than 20 (so it's one of the last three days of 2014)

    THEN (calculate the week of your date minus 5 days, and add 1).

    This will make the last few days of the year into their own week, which is sometimes week 52, sometimes week 53. And it works with European and US calendars.

    You'll need to think what you want to do if Jan 1st is in the last week of the previous year. Might make it week 0. So really going with the standard and accepting what iOS tells you is the saner way to do it.

    0 讨论(0)
提交回复
热议问题