2

对于 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 格式化程序集成到此类别中也很有帮助。

4

1 回答 1

0

是的,不少人在 NSDate 上建立了类别。

您可以通过搜索 github 找到其中的一些:https ://github.com/search?langOverride=&q=nsdate&repo=&start_value=1&type=Repositories

于 2012-05-15T17:29:40.730 回答