Как создать объект даты NSDate? - PullRequest
16 голосов
/ 11 ноября 2010

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

Ответы [ 3 ]

38 голосов
/ 11 ноября 2010

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

//  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];

12 голосов
/ 11 ноября 2010

Вы можете использовать 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];
5 голосов
/ 11 ноября 2010

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

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's other use, for UI work

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

NSDate *dateFromString = [dateFormatter dateFromString:stringContainingDate];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...