Getting first and last days of current week

不羁岁月 提交于 2019-12-22 12:28:00

问题


How can I get first and last days of the current week? What I need is some way of filtering a set of objects with NSDate property to leave only ones, that appear on current week, and then filter them by days. Also I need some way to get localized day names.

I've tried to play with NSCalendar, NSDate and NSDateComponents, but it seems that I can't just check calendar's firstWeekday, as there might be weeks with days from previous/next month.


回答1:


Use NSDateComponents to get the weekday, which is from 1 for Sunday to 7.

Once you have the weekday number, calculate the difference between it, and your first day of the week. For instance if you consider Monday (2) to be the first day, then how many days earlier was it (or would it be). If the weekday is 4 (Wed) then the difference is 2. This means that if you subtract two days from the original date, you will get the first day of the week that it lies in.

Check the documentation for details, because you will need to deal with the fact that these object also include time attributes. If you can, make sure that the time values are always zero when you are only interested in dates and date comparisons.




回答2:


Ok, here it goes, a python snippet that does 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's first day midnight
    return (firstDt, lastDt)


来源:https://stackoverflow.com/questions/1625098/getting-first-and-last-days-of-current-week

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!