Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
277 views
in Technique[技术] by (71.8m points)

ios - Wrong Year and weekOfYear in Gregorian Calendar objective-c

+ (NSCalendar*)getGregorianCalendarInstance {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    return calendar;
}

+ (NSInteger)currentGregorianWeekOfYear:(NSDate*) date {
    NSCalendar *gregorianCalendar = [self getGregorianCalendarInstance];
    gregorianCalendar.firstWeekday = 2; // Monday = 2
    NSDateComponents *components = [gregorianCalendar components:NSCalendarUnitWeekOfYear fromDate:date];
    NSUInteger weekOfYear = [components weekOfYear];
    return weekOfYear;
}

+ (NSInteger)currentGregorianYear:(NSDate*) date {
    NSCalendar *gregorianCalendar = [self getGregorianCalendarInstance];
    gregorianCalendar.firstWeekday = 2;
    [gregorianCalendar setTimeZone:[NSTimeZone defaultTimeZone]];
    gregorianCalendar.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
    NSDateComponents *comps = [gregorianCalendar components: NSCalendarUnitYear  fromDate:date];
    NSInteger year = [comps year];
    return year;
}

week number returns 52 instead of 1 in currentGregorianWeekOfYear function and year returns 2019 instead of 2020 in currentGregorianYear function for date = 2019-12-30 15:00:00 +0000

Specific reason to use the Gregorian calendar is to display 1st January in the 1st week of the year. With the ISO calendar, 1st January will be indicated as the 52nd or 53rd week of the year.

I already checked multiple references but it does not solve my problem:

  1. WeekOfYear overflowing to 1 in 53rd week in gregorian calendar?
  2. NSDateComponents weekOfYear returns wrong value
  3. Swift: Gregorian Calendar and weeks/weekdays - inconsistent behavior
question from:https://stackoverflow.com/questions/65951784/wrong-year-and-weekofyear-in-gregorian-calendar-objective-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...