Getting the first and last days of the current week

How can I get the first and last days of the current week? I need some way to filter a set of objects using the NSDate property, to leave only those that appear this week, and then filter them by day. I also need a way to get localized day names.

I tried to play with NSCalendar, NSDate and NSDateComponents, but it seems that I can’t just check the firstWeekday calendar, as there may be weeks with days of the previous / next month.

+2
source share
2 answers

Ok, here it is, a piece of python doing the job

def daySec(diff):
    return 60*60*24*diff

def weekDays(dt=None):
    if not dt:
        dt = NSDate.date() # use today
    cal = NSCalendar.currentCalendar()
    dc = cal.components_fromDate_(NSWeekdayCalendarUnit|NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit, dt)
    normDt = cal.dateFromComponents_(dc) # get the day-rounded date
    shift = dc.weekday() - cal.firstWeekday()
    firstDt = normDt.dateByAddingTimeInterval_(daySec(-shift))
    lastDt = normDt.dateByAddingTimeInterval_(daySec(-shift+7)) # up to next week first day midnight
    return (firstDt, lastDt)
0

NSDateComponents , 1 7.

, ​​. , , (2) , ( ). 4 (.), 2. , , , .

, , . , , , .

+3

Source: https://habr.com/ru/post/1728845/


All Articles