6

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.

ohaal
  • 5,208
  • 2
  • 34
  • 53
rudasagani
  • 157
  • 2
  • 12

1 Answers1

13

This line is the problem:

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

It should be

NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];
Shmidt
  • 16,436
  • 18
  • 88
  • 136
sosborn
  • 14,676
  • 2
  • 42
  • 46