使用自定义日期初始化NSDate

Car*_*rlo 8 objective-c

我正在寻找类似的东西:

NSDate *date = [[NSDate alloc] initWithYear:1984 month:10 Day:8];
Run Code Online (Sandbox Code Playgroud)

有没有办法做这样的事情?

谢谢!

Mat*_*uch 20

我为这个任务写了一个类别.NSDate缺少许多有用的方法.

@interface NSDate (missingFunctions) 
+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day;
@end


@implementation NSDate (missingFunctions)

+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
    [components setYear:year];
    [components setMonth:month];
    [components setDay:day];
    return [calendar dateFromComponents:components];
}   
@end
Run Code Online (Sandbox Code Playgroud)

  • 它不会错过.故意不在那里.该理论认为,假设的"+ [NSDate dateWithYear:month:day:]"会使开发人员预先假定每个人都使用格里高利历.更好的是,在Apple的脑海中,将实时日历操作(`NSCalendar`和`NSDateComponents`)中的时间操作(`NSDate`)分开. (7认同)