当我尝试使当前周日期显示在日志中时(周一到周日),就像一周从周日开始。
例如:
本周是 38 号。
昨天是9月20日。我的代码确实显示了从星期一到星期日的正确日期。
但是今天(9 月 21 日)我的日志显示下周日期(第 39 周),此时仍是第 38 周。

我的代码:

NSDate *currentDate = [NSDate date];
NSCalendar *myCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *currentComps = [myCalendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekOfYearCalendarUnit | NSWeekdayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit) fromDate:currentDate];
int thisWeeksNumber = currentComps.weekOfYear;
NSLog(@"1  %d", thisWeeksNumber);

[currentComps setWeekday:2];

NSDate *firstDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
NSDate *secondDayOfTheWeek = [self dateByAddingDays:1 toDate:firstDayOfTheWeek];
NSDate *thirdDayOfTheWeek = [self dateByAddingDays:2 toDate:firstDayOfTheWeek];
NSDate *fourthDayOfTheWeek = [self dateByAddingDays:3 toDate:firstDayOfTheWeek];
NSDate *fifthDayOfTheWeek = [self dateByAddingDays:4 toDate:firstDayOfTheWeek];
NSDate *sixthDayOfTheWeek = [self dateByAddingDays:5 toDate:firstDayOfTheWeek];
NSDate *seventhDayOfTheWeek = [self dateByAddingDays:6 toDate:firstDayOfTheWeek];

NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
myDateFormatter.dateFormat = @"yyyy-MM-dd";
NSString *firstStr = [myDateFormatter stringFromDate:firstDayOfTheWeek];
NSString *secondStr = [myDateFormatter stringFromDate:secondDayOfTheWeek];
NSString *thirdStr = [myDateFormatter stringFromDate:thirdDayOfTheWeek];
NSString *fourthStr = [myDateFormatter stringFromDate:fourthDayOfTheWeek];
NSString *fifthStr = [myDateFormatter stringFromDate:fifthDayOfTheWeek];
NSString *sixthStr = [myDateFormatter stringFromDate:sixthDayOfTheWeek];
NSString *seventhStr = [myDateFormatter stringFromDate:seventhDayOfTheWeek];

NSLog(@"\n %@ \n %@ \n %@ \n %@ \n %@ \n %@ \n %@", firstStr, secondStr, thirdStr, fourthStr, fifthStr, sixthStr, seventhStr);
}

还有我的 NSDate 方法:
- (NSDate*)dateByAddingDays:(NSInteger)days toDate:(NSDate *)date
{
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.day = days;

return [calendar dateByAddingComponents: comps toDate: date options: 0];
}

这应该全天显示第 38 周,但它显示下周日期,因为它是星期日。
(当我写这篇文章时,现在是第 38 周,也就是 9 月 21 日)

最佳答案

您需要使用 NSUInteger2 参数值调用 setFirstWeekday: (星期日是 1 )

[myCalendar setFirstWeekday:2];

关于ios - 如何让 NSCalendar 周从周一而不是周日开始,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25961522/

10-09 19:36