How can I generate convenient date ranges based on a given NSDate?

后端 未结 2 1801
有刺的猬
有刺的猬 2021-02-01 11:14

I\'m creating a report generator in Cocoa, and I need to produce convenient date ranges such as \"Today\", \"This Week\", \"This Month\", \"This Year\", etc.

Is there a

2条回答
  •  盖世英雄少女心
    2021-02-01 12:01

    For the sake of completeness, here is my final solution (with thanks to Kendall Helmstetter Geln and jbrennan):

    + (NSCalendar *)calendar
    {
        NSCalendar * gregorian = [[NSCalendar alloc]
                                  initWithCalendarIdentifier:NSGregorianCalendar];
        return [gregorian autorelease];
    }
    
    ////////////////////////////////////////////////////////////////
    
    + (NSDateComponents *)singleComponentOfUnit:(NSCalendarUnit)unit
    {
        NSDateComponents * component = [[NSDateComponents alloc] init];
    
        switch (unit)
        {
            case NSDayCalendarUnit: [component setDay:1]; break;
            case NSWeekCalendarUnit: [component setWeek:1]; break;
            case NSMonthCalendarUnit: [component setMonth:1]; break;
            case NSYearCalendarUnit: [component setYear:1]; break;
        }
    
        return [component autorelease];
    }
    
    ////////////////////////////////////////////////////////////////
    
    + (WM_DateRange *)rangeForUnit:(NSCalendarUnit)unit
                   surroundingDate:(NSDate *)date
    {
        WM_DateRange * range = [[self alloc] init];
    
        // start of the period
        NSDate * firstDay;
        [[self calendar] rangeOfUnit:unit
                           startDate:&firstDay
                            interval:0
                             forDate:date];
        [range setStartDate:firstDay];
    
        // end of the period
        [range setEndDate:[[self calendar]
            dateByAddingComponents:[self singleComponentOfUnit:unit]
                            toDate:firstDay
                           options:0]];
    
        return [range autorelease];
    }
    
    ////////////////////////////////////////////////////////////////
    
    + (WM_DateRange *)rangeForDayContainingDate:(NSDate *)date
    { return [self rangeForUnit:NSDayCalendarUnit surroundingDate:date]; }
    
    + (WM_DateRange *)rangeForWeekContainingDate:(NSDate *)date
    { return [self rangeForUnit:NSWeekCalendarUnit surroundingDate:date]; }
    
    + (WM_DateRange *)rangeForMonthContainingDate:(NSDate *)date
    { return [self rangeForUnit:NSMonthCalendarUnit surroundingDate:date]; }
    
    + (WM_DateRange *)rangeForYearContainingDate:(NSDate *)date
    { return [self rangeForUnit:NSYearCalendarUnit surroundingDate:date]; }
    
    ////////////////////////////////////////////////////////////////
    
    - (void)dealloc
    {
        [endDate release];
        [startDate release];
        [super dealloc];
    }
    

提交回复
热议问题