How to create an NSDate date object?

前端 未结 3 1547
迷失自我
迷失自我 2021-02-05 10:26

How can I create an NSDate from the day, month and year? There don\'t seem to be any methods to do this and they have removed the class method dateWithString<

3条回答
  •  失恋的感觉
    2021-02-05 10:52

    You could write a category for this. I did that, this is how the code looks:

    //  NSDateCategory.h
    
    #import 
    
    @interface NSDate (MBDateCat) 
    
    + (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day;
    
    @end
    
    
    
    //  NSDateCategory.m
    
    #import "NSDateCategory.h"
    
    @implementation NSDate (MBDateCat)
    
    + (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
    

    Use it like this: NSDate *aDate = [NSDate dateWithYear:2010 month:5 day:12];

提交回复
热议问题