2010-10-08 80 views

回答

6

對於time/date calculations使用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]; 

2014年3月

其實還有一個更聰明的方式

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 

如果你確實改變平日代表本週的開始(週日vs 。星期一),你應該在這段代碼後改回它。

+0

看起來很複雜:>。但它是一個非常好的例子。謝謝 – adamseve 2010-10-08 14:01:58