There are two different aspects in your question. First,
NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2014];
[dateComponents setMonth: 1];
[dateComponents setDay: 31];
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* otherDay = [calendar dateFromComponents: dateComponents];
computes otherDay
as "2014-01-31 00:00" (in your time zone), and
NSDate *todaydate = [NSDate date];
computes todaydate
as the current point in time, which includes the hours, minutes
and seconds, for example "2014-01-31 13:00:00" (in your time zone). Therefore
[otherDay compare:todaydate]
returns NSOrderedAscending
: otherDay
is earlier than todaydate
!
What you probably want is to compute todaydate
as the start of the current day
(today at 00:00). This can be done as
NSDate * todaydate;
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&todaydate interval:NULL forDate:[NSDate date]];
And now [otherDay compare:todaydate]
returns NSOrderedSame
, as you expected.
The other aspect is the NSLog
output. Printing a NSDate
with NSLog()
prints the date according to GMT, and "2014-01-31 00:00" in your time zone is
exactly the same time as "2014-01-30 18:30:00 +0000" in GMT.
The output is correct, it just uses GMT instead of your local timezone for display.