gpt4 book ai didi

ios - 我怎样才能在 Objective-C 的特殊日期获得一周中的星期一?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:21:13 25 4
gpt4 key购买 nike

例如2010 年 10 月 1 日是星期五 => 2010 年 9 月 27 日是星期一。

我不知道如何管理这个。顺便说一句:我如何计算日期?

最佳答案

对于 time/date calculations使用 NSDateComponents。

list 2 获取当前周的星期日

NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

// Get the weekday component of the current date
NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today];

/*
Create a date components to represent the number of days to subtract from the current date.
The weekday value for Sunday in the Gregorian calendar is 1, so subtract 1 from the number of days to subtract from the date in question. (If today's Sunday, subtract 0 days.)
*/
NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 1)];

NSDate *beginningOfWeek = [gregorian dateByAddingComponents:componentsToSubtract toDate:today options:0];

/*
Optional step:
beginningOfWeek now has the same hour, minute, and second as the original date (today).
To normalize to midnight, extract the year, month, and day components and create a new date from those components.
*/
NSDateComponents *components =
[gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate: beginningOfWeek];
beginningOfWeek = [gregorian dateFromComponents:components];

在以后的版本中,有一个更聪明的方法:

NSCalendar *cal = [NSCalendar currentCalendar];
[cal setFirstWeekday:2]; //2 is monday. 1:Sunday .. 7:Saturday don't set it, if user's locale should determine the start of a week
NSDate *now = [NSDate date];
NSDate *monday;
[cal rangeOfUnit:NSWeekCalendarUnit // we want to have the start of the week
startDate:&monday // we will write the date object to monday
interval:NULL // we don't care for the seconds a week has
forDate:now]; // we want the monday of today's week

如果您实际上更改了代表一周开始的工作日(星期日与星期一),您应该在此代码段之后将其改回。

关于ios - 我怎样才能在 Objective-C 的特殊日期获得一周中的星期一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3891104/

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