Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an NSDate date object?

Tags:

objective-c

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?!).

like image 780
TheLearner Avatar asked Nov 11 '10 11:11

TheLearner


People also ask

How do I get today's date in Objective C?

Get Today's Date:NSDate* date = [NSDate date];

What is NS date?

Overview. NSDate objects encapsulate a single point in time, independent of any particular calendrical system or time zone. Date objects are immutable, representing an invariant time interval relative to an absolute reference date (00:00:00 UTC on 1 January 2001).

How do you create a date variable in Swift?

Creating a Date and Time in Swift Of course, it would be easier to use things like years, months, days and hours (rather than relative seconds) to make a Date . For this you can use DateComponents to specify the components and then Calendar to create the date. The Calendar gives the Date context.

How does Objective C compare to NSDate?

There are 4 methods for comparing NSDate s in Objective-C: - (BOOL)isEqualToDate:(NSDate *)anotherDate. - (NSDate *)earlierDate:(NSDate *)anotherDate. - (NSDate *)laterDate:(NSDate *)anotherDate.


2 Answers

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

like image 186
Matthias Bauch Avatar answered Oct 03 '22 12:10

Matthias Bauch


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];
like image 23
Pablo Santa Cruz Avatar answered Oct 03 '22 13:10

Pablo Santa Cruz