开发者

How to determine the startdate (monday) of a week with a predefined date?

开发者 https://www.devze.com 2023-01-19 06:20 出处:网络
My example date is 08.10.2010 (friday), so the startdate should be 04.10.2010 (monday). 开发者_如何学CNSDate *today = [[NSDate alloc] init];

My example date is 08.10.2010 (friday), so the startdate should be 04.10.2010 (monday).

开发者_如何学C
NSDate *today = [[NSDate alloc] init];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *weekdayComponents = [gregorian components:NSWeekdayCalendarUnit fromDate:today];

NSDateComponents *componentsToSubtract = [[NSDateComponents alloc] init];
[componentsToSubtract setDay: 0 - ([weekdayComponents weekday] - 2)];

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

NSLog(@"%@", beginningOfWeek);

The problem with this code-snippet is, that the week starts with sunday. This means, if I use the date 10.10.2010 (sunday) I also get 10.10.2010 as the start of the week, but it should be 04.10.2010 (monday). What is wrong with this code? Or are there other better solutions to solve this problem?

0

精彩评论

暂无评论...
验证码 换一张
取 消