Как создать объект даты NSDate?

Как я могу создать NSDate из дня, месяца и года? Кажется, что нет никаких методов для этого, и они удалили метод класса dateWithString (зачем им это делать?!).

Ответы

Ответ 1

Вы можете написать категорию для этого. Я сделал это, вот как выглядит код:

//  NSDateCategory.h

#import <Foundation/Foundation.h>

@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

Используйте его следующим образом: NSDate *aDate = [NSDate dateWithYear:2010 month:5 day:12];

Ответ 2

Вы можете использовать NSDateComponents:

NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:6];
[comps setMonth:5];
[comps setYear:2004];
NSCalendar *gregorian = [[NSCalendar alloc]
    initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *date = [gregorian dateFromComponents:comps];
[comps release];

Ответ 3

Несколько другой ответ на уже опубликованные; если у вас есть фиксированный формат строки, который вы хотите использовать для создания дат, вы можете использовать что-то вроде:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];

dateFormatter.locale = [NSLocale localeWithIdentifier:@"en_US_POSIX"]; 
    // see QA1480; NSDateFormatter otherwise reserves the right slightly to
    // modify any date string passed to it, according to user settings, per
    // it other use, for UI work

dateFormatter.dateFormat = @"dd MMM yyyy"; 
    // or whatever you want; per the unicode standards

NSDate *dateFromString = [dateFormatter dateFromString:stringContainingDate];