Question

I am trying to compare 2 Dates but in i am getting 1 day less

here is a snippet:

NSDateComponents* dateComponents = [[NSDateComponents alloc] init];

[dateComponents setYear: 2014];
[dateComponents setMonth: 1];
[dateComponents setDay: 31];

NSCalendar* calendar = [NSCalendar currentCalendar];

NSDate* otherDay = [calendar dateFromComponents: dateComponents];


NSDate * todaydate= [NSDate date];

if ([otherDay compare:todaydate]>= NSOrderedDescending)
{
    NSLog(@"In If other Date= %@ & Today = %@ ", otherDay,todaydate);
}else
{
    NSLog(@"I am in else other date= %@ and today = %@ ",otherDay, todaydate);
}

The Log i am getting is :

I am in else other date= 2014-01-30 18:30:00 +0000 and today = 2014-01-31 08:34:21 +0000

Why it's showing other date = 30th jan 2014 ?

Was it helpful?

Solution

You need to set timezone of NSDateComponents such like,

[dateComponents setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

Or as trojanfoe's suggestion you can also set timezone of NSCalendar such like,

[calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];

And To exact compare otherDay to todaydate please see answer of Martin R you need to set

NSDate * todaydate;
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&todaydate interval:NULL forDate:[NSDate date]];

From Martin R's answer this is very useful.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top