如何创建NSDate日期对象?

时间:2010-11-11 11:50:43

标签: objective-c

如何从日,月和年创建NSDate?似乎没有任何方法可以做到这一点,他们已经删除了类方法dateWithString(为什么他们会这样做?!)。

3 个答案:

答案 0 :(得分:38)

你可以为此写一个类别。我这样做了,这就是代码的样子:

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

答案 1 :(得分:12)

您可以使用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];

答案 2 :(得分:5)

对已发布的答案略有不同;如果你有一个固定的字符串格式,你想用来创建日期,那么你可以使用类似的东西:

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