tatsuos
2/3/2015 - 6:23 AM

月始・月末取得

月始・月末取得

#import "NSDate+TSDate.h"

@implementation NSDate (TSDate)

- (NSDate *)ts_BOM
{
    if (!self) {
        return nil;
    }

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [calendar components:NSYearCalendarUnit
                                    | NSMonthCalendarUnit
                                    | NSDayCalendarUnit
                                    | NSHourCalendarUnit
                                               fromDate:self];
    NSInteger year = [components year];
    NSInteger month = [components month];

    NSDateComponents *retComponents = [[NSDateComponents alloc] init];

    [retComponents setYear:year];
    [retComponents setMonth:month];

    return [calendar dateFromComponents:retComponents];
}

- (NSDate *)ts_EOM
{
    if (!self) {
        return nil;
    }

    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

    NSDateComponents *components = [calendar components:NSYearCalendarUnit
                                               | NSMonthCalendarUnit
                                               | NSDayCalendarUnit
                                               | NSHourCalendarUnit
                                               fromDate:self];
    NSInteger year = [components year];
    NSInteger month = [components month];

    NSDateComponents *retComponents = [[NSDateComponents alloc] init];

    [retComponents setYear:year];
    [retComponents setMonth:month];

    NSRange range = [calendar rangeOfUnit:NSDayCalendarUnit inUnit:NSMonthCalendarUnit forDate:self];
    [retComponents setDay:range.length];

    return [calendar dateFromComponents:retComponents];
}


@end
#import <Foundation/Foundation.h>

@interface NSDate (TSDate)

- (NSDate *)ts_BOM;
- (NSDate *)ts_EOM;

@end