如何计算当前第一周的NSDate?

ohh*_*hho 14 iphone cocoa-touch nsdate

即:

  NSDate *firstDayOfWeek = [[NSDate date] firstDayOfWeek];
Run Code Online (Sandbox Code Playgroud)

例如,今天是8月19日,我想为一个NSDate2010-08-15 12:00am从上面的代码行.谢谢!

Thi*_*tte 36

我认为这些主题可以满足您的需求: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];
Run Code Online (Sandbox Code Playgroud)

  • 请注意,日历的命名可能有点误导.在大多数情况下,currentCalendar将是Gregorian,但没有为任何语言环境定义.相反,我只会将指针命名为_calendar_. (3认同)

Rud*_*vič 22

为什么这么复杂?:)

func firstDateOfWeekWithDate(date: NSDate) -> NSDate {

    var beginningOfWeek: NSDate?

    calendar.rangeOfUnit(.WeekOfYear, startDate: &beginningOfWeek, interval: nil, forDate: date)

    return beginningOfWeek!

}
Run Code Online (Sandbox Code Playgroud)


Wol*_*ang 11

如果星期一(2)设置为第一周,并且您正在检查的日期是星期日,则naixn的解决方案将产生错误的结果.在这种情况下,你将得到下周一的星期一.

正确的方法是按如下方式计算减法分量:

[componentsToSubtract setDay: - ((([weekdayComponents weekday] - [gregorian firstWeekday])
                                  + 7 ) % 7)];
Run Code Online (Sandbox Code Playgroud)

假设你一周有7天.