如何创建NSDate日期对象?

The*_*ner 16 objective-c

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

Mat*_*uch 40

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

//  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
Run Code Online (Sandbox Code Playgroud)

像这样使用它: NSDate *aDate = [NSDate dateWithYear:2010 month:5 day:12];

  • 它只是让我想到了为了在目标C中创建日期而需要编写的代码量! (10认同)
  • 辩护理由是NSDate唯一地识别地球历史中的一个时刻.有很多方法可以写日期(今天常用,至少是格里高利,希伯来和伊斯兰日历),所以这是一个单独的逻辑事物.在Cocoa中,您使用NSCalendar对象来消除歧义.成本是你可能希望成为一行代码最终成为六行,这就像在fluchtpunkt的答案中一样 - 很容易松散到库代码中. (2认同)

Pab*_*ruz 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];
Run Code Online (Sandbox Code Playgroud)


Tom*_*mmy 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];
Run Code Online (Sandbox Code Playgroud)