本文介绍了获得本周的第一天和最后几天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获得当周的第一天和最后几天?我需要的是一些方法使用NSDate属性过滤一组对象,只留下一些,出现在当前周,然后按天过滤它们。

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.

我试图使用NSCalendar,NSDate和NSDateComponents,但似乎我不能只检查日历的

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.

推荐答案

好的,这里是一个Python代码片段

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)

这篇关于获得本周的第一天和最后几天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-27 16:46
查看更多