Как рассчитать первое NSDate текущей недели?

, например:

  NSDate *firstDayOfWeek = [[NSDate date] firstDayOfWeek];

, например, сегодня 19 августа, я бы хотел получить NSDate из 2010-08-15 12:00 утра сверху строки кода. Спасибо!

14
задан Suresh.D 4 February 2011 в 06:02
поделиться

2 ответа

Я думаю, что эти потоки отвечают на то, что вы ищете: http://www.cocoabuilder.com/archive/cocoa/211648-nsdatecomponents-question. html # 211826

Однако обратите внимание, что он не обрабатывает понедельники как первые дни недели, поэтому вам, возможно, придется немного подправить его, вычтя [gregorian firstWeekday] вместо только 1 . Кроме того, я модифицировал его для использования -currentCalendar , но это зависит от вас: -)

NSDate *today = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];

// 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];
/* Substract [gregorian firstWeekday] to handle first day of the week being something else than Sunday */
[componentsToSubtract setDay: - ([weekdayComponents weekday] - [gregorian firstWeekday])];
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];
36
ответ дан 1 December 2019 в 05:51
поделиться

Используйте NSDateComponents и установите weekday в 1.

0
ответ дан 1 December 2019 в 05:51
поделиться
Другие вопросы по тегам:

Похожие вопросы: