+ (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:
- WeekOfYear overflowing to 1 in 53rd week in gregorian calendar?
- NSDateComponents weekOfYear returns wrong value
- Swift: Gregorian Calendar and weeks/weekdays - inconsistent behavior
question from:
https://stackoverflow.com/questions/65951784/wrong-year-and-weekofyear-in-gregorian-calendar-objective-c 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…