Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I initialize a date to NSdate?

Tags:

iphone

I want to give, for example, 12/11/2005 in the format of mm/dd/yyyy. Can I initialize 12/11/2005 to NSDate directly? Any help?

it gives a warning and crashes when I declare it as

NSDate *then = [NSDate dateWithNaturalLanguageString:02/11/2009  locale:nil];
like image 881
senthilM Avatar asked Nov 25 '09 08:11

senthilM


People also ask

What is NS date?

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 I get the current date and time in Objective C?

NSDate and NSDateFormatter classes provide the features of date and time. NSDateFormatter is the helper class that enables easy conversion of NSDate to NSString and vice versa.

How do I print the time in Objective C?

NSDate *date = [NSDate date]; to get the current date and time. Use NSDateFormatter to format it. See this link for a how-to on date and time formatting.


2 Answers

Another solution could be the use of NSCalendar and NSDateComponents, since +dateWithNaturalLanguageString: is deprecated.

For example you want a NSDate initialised to 15th of August 2001. This is the code that will work for you:

NSCalendar *g = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

NSDateComponents *comps = [[NSDateComponents alloc] init];
comps.year = 2001;
comps.month = 8;
comps.day = 15;

NSDate *myDate = [g dateFromComponents:comps];

or another way is:

let earliestDate = calendar.dateWithEra(1, year: 2012, month: 1, day: 1, hour: 0, minute: 0, second: 0, nanosecond: 0)

to set the earliestDate NSDate to 01/01/2012

like image 83
angelos.p Avatar answered Oct 18 '22 16:10

angelos.p


What you need to do is something like this:

NSDateFormatter *mmddccyy = [[NSDateFormatter alloc] init];
mmddccyy.timeStyle = NSDateFormatterNoStyle;
mmddccyy.dateFormat = @"MM/dd/yyyy";
NSDate *d = [mmddccyy dateFromString:@"12/11/2005"];
NSLog(@"%@", d);
like image 21
Zoran Simic Avatar answered Oct 18 '22 15:10

Zoran Simic