Avinash
Avinash

Reputation: 47

iphone Convert NSDate from server to local device time and compare

I am accessing a server data at particular time which is in different timezone, I need to compare this date with my device time and show some recent updates to user.

ServerTime i am getting as below.

enter code here
     NSString *localString = @"2012-02-10T23:53:46+0000";
     NSString *serverTime = @"2012-02-11T06:17:39+0000";

     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
     [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
    NSDate* sourceDate = [dateFormatter dateFromString:serverTime];

    NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

    NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];


    NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];

     NSLog(@"Source OFFSET %i",sourceGMTOffset)
     NSLog(@"Desti OFFSET %i",destinationGMTOffset);

     NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

     NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] ;

    NSString *thePubDate =  [dateFormatter stringFromDate:destinationDate];
    NSLog(@"Result : %@",thePubDate);
    [dateFormatter release];

Upvotes: 1

Views: 1080

Answers (1)

Matthias Bauch
Matthias Bauch

Reputation: 90117

Your dateFormat does not match the format of your date string. Read about the Unicode Date Format Patterns.
And after that try @"yyyy-MM-dd'T'HH:mm:ssZZZ"

But I think you try to do something wrong anyway.
A NSDate is a point in time, it is the same for every place in the world. You don't need to calculate a new NSDate just because your source is in a different timezone.

Use the dateFormat from above and compare it directly to a different NSDate.

Probably something like this:

NSString *serverTime = @"2012-01-11T06:17:39+0000";

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZ"];
NSDate* sourceDate = [dateFormatter dateFromString:serverTime];
if (!sourceDate) {
    NSLog(@"Wrong NSDateFormatter format!");
}
else {
    NSDate *date24HoursAgo = [NSDate dateWithTimeIntervalSinceNow:-(24*60*60)];
    NSLog(@"%@", sourceDate);
    NSLog(@"%@", date24HoursAgo);
    if ([sourceDate compare:date24HoursAgo] == NSOrderedAscending) {
        NSLog(@"Timestamp from server is older than 24 hours.");
    }
}

Upvotes: 2

Related Questions