How to create an NSDate date object?

前端 未结 3 1549
迷失自我
迷失自我 2021-02-05 10:26

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<

相关标签:
3条回答
  • 2021-02-05 10:31

    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];
    
    0 讨论(0)
  • 2021-02-05 10:41

    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];
    
    0 讨论(0)
  • 2021-02-05 10:52

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

    0 讨论(0)
提交回复
热议问题