rudasagani
rudasagani

Reputation: 157

How to determine day, month, and year as int in iOS

I want to determine day, month, and year of current date in iOS. I found this after a search on the net:

NSDate *date = [NSDate date];
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [calendar components:(NSDayCalendarUnit) fromDate:date];
NSInteger Day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];

This code shows the day correct, but the year and month is not showing as it should be. It shows some digits like 2147483647. I could not find a solution so please help me correct the code I found, or write some new code which does what I need.

Upvotes: 6

Views: 6625

Answers (1)

sosborn
sosborn

Reputation: 14694

This line is the problem:

NSDateComponents *components = [calendar components:(NSDayCalendarUnit) fromDate:date];

It should be

NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];

Upvotes: 13

Related Questions