Different result for [NSDate date] in several devices

gcdasyncsocket, ios, iphone, nsdate, udp

Solution

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss"];
[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
NSString *strSystemTime = [dateFormatter stringFromDate:[NSDate date]];

I faced the same issue and resolved it by setting NSLocale. I hope this solution works for you too.

Problem

To start, I have to say that I set autoset in date&time settings and time zone is the same for each device. So I use `[NSDate date]` to get time stamp in milliseconds, then encode to `NSData` and send to another device. On receiver data is being decoded and subtract with new `[NSDate date]`. So that I get total time needed for send and receive message. That I was thought because when sender is iPhone 4 iOS6 and receiver is iPhone 5 iOS7 then receiver have earlier time stamp than sender. I don't know why? Maybe `[NSData date]` isn't the most reliable class for that kind of operations? I use `GCDAsyncUdpSocket` for sending/receiving UDP. Code sender ``` NSData *data2 = [self createRandomNSData:8192]; NSMutableData *dataToSend =[NSMutableData data]; [dataToSend appendBytes:&tag length:sizeof(int)]; long long currentTimeStamp = (long long)([[NSDate date] timeIntervalSince1970]*1000.0); [dataToSend appendBytes:&currentTimeStamp length:sizeof(long long)]; [dataToSend appendData:data2]; NSLog(@"%i || %lld || %lu",tag, currentTimeStamp,(unsigned long)[dataToSend length]); [_udpSocket sendData:dataToSend toHost:@"230.0.0.1" port:_port withTimeout:-1 tag:tag]; tag++; ``` Code receiver ``` char* dataBytes = [data bytes]; int inTag; long long inCurrentTimeStamp; [data getBytes:&inTag length:sizeof(int)]; [data getBytes:&inCurrentTimeStamp range:NSMakeRange(sizeof(int), sizeof(long long))]; long long currentTimeStamp = (long long)([[NSDate date] timeIntervalSince1970]*1000.0); long long timeStampDiff = currentTimeStamp - inCurrentTimeStamp; self.delay = timeStampDiff; NSLog(@"%i || %lld || %lu",inTag, timeStampDiff,(unsigned long)[data length]); ```

Original source