Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
271 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 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...