簡體   English   中英

如何在Objective-C中的特殊日期獲得一周中的星期一?

[英]How can I get the monday of a week in a special date in Objective-C?

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

我不知道該如何管理。 順便說一句:如何計算日期?

對於時間/日期計算,請使用NSDateComponents。

清單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

如果您實際上更改了代表一周開始時間的工作日(星期日與星期一),則應在此代碼段之后將其改回。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM