gpt4 book ai didi

ios - 如何使 NSCalendar 周从星期一而不是星期日开始

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:58:03 34 4
gpt4 key购买 nike

当我尝试使当前周日期显示在日志中(周一至周日)时,就像一周从周日开始一样。例如:这周是 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 日)

最佳答案

您需要调用setFirstWeekday: NSUInteger 参数值为 2(星期日为 1)

[myCalendar setFirstWeekday:2];

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

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com