I'm the confusion with converting NSTimeInterval
to NSDate
, I've two dates to compare, one is coming from server and another is in local,
In server case, I'm getting date in time interval format, so I've to do the same with local too.
I'm taking 3rd July 2014 for testing,
I'm doing the conversion in this way,
//converting NSString to NSDate and then to NSTimeInterval
NSLog(@"Local Time Stamp:%.f",[[self dateFromString:@"03-07-2014"] timeIntervalSince1970]);
//Server time stamp
NSLog(@"Server Time Stamp:1404360000");
//converting to NSDate from NSTimeInterval (for local)
NSLog(@"%@",[self converToDateFromString:[NSString stringWithFormat:@"%.f",[[self dateFromString:@"03-07-2014"] timeIntervalSince1970]]]);
//converting to NSDate from NSTimeInterval (for server)
NSLog(@"%@",[self converToDateFromString:@"1404360000"]);
Output,
2014-07-21 17:26:50.964 MyApp[998:90b] Local Time Stamp:1404325800
2014-07-21 17:26:52.633 MyApp[998:90b] Server Time Stamp:1404360000
2014-07-21 17:26:58.130 MyApp[998:90b] Local Time Stamp To Date:2014-07-02 18:30:00 +0000
2014-07-21 17:26:59.880 MyApp[998:90b] Server Time Stamp To Date:2014-07-03 04:00:00 +0000
see the dates are same but it's time is different. It may be because of time zone?
if([localDate isEqualToDate:serverDate]) {
NSLog(@"Matched!");
}else{
NSLog(@"Unmatched!");
}
Is always Unmatched!
Any suggestions to compare it? Also, why server time interval and local time interval is different? I think because of this I can't comparing the dates.
For a note, I'm using the below methods which used to convert time stamp to date, string to date. As used in above code.
- (NSDate *)dateFromString:(NSString *)dateString {
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setTimeZone: [NSTimeZone timeZoneWithAbbreviation:[[NSTimeZone localTimeZone] abbreviation]]];
[df setDateFormat:@"dd-MM-yyyy"];
return [df dateFromString:dateString];
}
-(NSDate *)converToDateFromString:(NSString *)str
{
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[str integerValue]];
return date;
}
You have to convert both the dates in gmt format using:
[df setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
[df setDateFormat:@"dd-MM-yyyy"];
and then compare the dates strings
I'm making time zone abbreviation more dynamic to user's speicified in setting,
So [df setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];
should be replace with this,
[df setTimeZone: [NSTimeZone timeZoneWithAbbreviation:[[NSTimeZone localTimeZone] abbreviation]]];