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?!).
Get Today's Date:NSDate* date = [NSDate 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).
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.
There are 4 methods for comparing NSDate s in Objective-C: - (BOOL)isEqualToDate:(NSDate *)anotherDate. - (NSDate *)earlierDate:(NSDate *)anotherDate. - (NSDate *)laterDate:(NSDate *)anotherDate.
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];
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With