iOS の場合、一般的に使用される日付関連の操作用に NSDate 拡張機能を作成した人はいますか? これまでに行ったことを以下に示します。ここはもっと想像できます。
#import <Foundation/Foundation.h>
@interface NSDate (Utilities)
// daysOffsetBy -- denotes how many days to offset the current date
// before calculating midnight. Here are some examples of how this
// parameter works:
//
// - if 0, then get the next immediate midnight.
// - if -1, then get yesterday's midnight (ie, early morning today).
// - if +1, then get tomorrow's mignight.
- (NSDate *)midnight:(NSInteger)daysOffsetBy;
// Use this method to transpose a time-of-day, specified in self,
// to an arbitrary reference date, specified in refDate. For example,
// suppose the time-of-day in self is 10:30 AM, and the calendar date
// is 1995-07-21. Suppose further that the calendar date for refDate
// is 2012-05-22, and that the time-of-day for refDate is 17:00 PM.
// This method creates a new date: 2012-05-22 10:30 AM.
- (NSDate *)transposeToDate:(NSDate *)refDate;
// Return YES if the
- (BOOL) occursInside:(NSDate *)fromTime throughTime:(NSDate *)toTime;
@end
対応する実装で:
#import "NSDate+Utilities.h"
static double SECONDS_IN_DAY = 24*60*60;
@implementation NSDate (Utilities)
- (NSDate *)midnight:(NSInteger)daysOffsetBy {
NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *refDate = [NSDate dateWithTimeInterval:(SECONDS_IN_DAY * daysOffsetBy) sinceDate:self];
NSDateComponents *components = [gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit |
NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:refDate];
[components setHour:0];
[components setMinute:0];
[components setSecond:0];
NSDate *retval = [gregorian dateFromComponents:components];
return retval;
}
- (NSDate *)transposeToDate:(NSDate *)refDate {
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate:self];
double secondsTranspiredInDay = [components second] + [components minute] * 60 + [components hour] * 60 * 60;
NSDate *retDate = [NSDate dateWithTimeInterval:secondsTranspiredInDay sinceDate:[refDate midnight:0]];
return retDate;
}
- (BOOL) occursInside:(NSDate *)fromTime throughTime:(NSDate *)toTime {
BOOL retval = NO;
NSComparisonResult c0 = [self compare:fromTime];
NSComparisonResult c1 = [self compare:toTime];
if ((c0 == NSOrderedSame || c0 == NSOrderedDescending) && (c1 == NSOrderedSame || c1 == NSOrderedAscending)) {
retval = YES;
}
return retval;
}
@end
addDays、addMinutes、addSeconds など、いくつかのエクストラは明らかです。NSDate フォーマッターをこのカテゴリに統合することも役立ちます。