gpt4 book ai didi

iphone - 获取一周的第一天和最后一天

转载 作者:行者123 更新时间:2023-12-01 19:12:47 26 4
gpt4 key购买 nike

我正在使用这种方法来获取当前星期的第一天和最后几天:

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

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

[currentComps setWeekday:1]; // 1: sunday
NSDate *firstDayOfTheWeek = [myCalendar dateFromComponents:currentComps];
[currentComps setWeekday:7]; // 7: saturday
NSDate *lastDayOfTheWeek = [myCalendar dateFromComponents:currentComps];

NSDateFormatter *myDateFormatter = [[NSDateFormatter alloc] init];
myDateFormatter.dateFormat = @"dd/MM/yyyy";
NSString *firstStr = [myDateFormatter stringFromDate:firstDayOfTheWeek];
NSString *secondStr = [myDateFormatter stringFromDate:lastDayOfTheWeek];

NSLog(@"first - %@ \nlast - %@", firstStr, secondStr);

我想知道我应该在此方面进行哪些更改,以便从下个星期的第一天,最后一天到现在的两周?

最佳答案

要获得下周的服务,请在firstDayOfTheWeek中添加7天,然后在lastDayOfTheWeek中添加7天。

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:7];
NSDate *firstDayOfNextWeek = [myCalendar dateByAddingComponents:comps toDate:firstDayOfTheWeek options:0];

该代码假定每周工作7天。理想情况下,您将用获得实际一周时间的代码替换此假设。

旁注:您的代码假定星期从星期日开始。许多语言环境在其他日期(例如星期一)开始工作。更改:
[currentComps setWeekday:1];

至:
[currentComps setWeekday:[myCalendar firstWeekday]];

然后,我将更改 lastDayOfTheWeek的计算,以将 firstDayOfWeek添加6天。

关于iphone - 获取一周的第一天和最后一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15314167/

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