TheLearner
TheLearner

Reputation: 19507

How to create an NSDate date object?

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 (why would they do that?!).

Upvotes: 17

Views: 19351

Answers (3)

Pablo Santa Cruz
Pablo Santa Cruz

Reputation: 181290

You can use 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];

Upvotes: 12

Tommy
Tommy

Reputation: 100632

A slightly different answer to those already posted; if you have a fixed string format you'd like to use to create dates then you can use something like:

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

Upvotes: 5

Matthias Bauch
Matthias Bauch

Reputation: 90117

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

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

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

Upvotes: 40

Related Questions