itay83
itay83

Reputation: 410

Applying NSDate from server with localtimezone get NSDate

I'm returning an NSDate from my server (running on GMT+2) I'm calculating few things with the server's date and the device current date.

The problem (obviously) is when the device is running on different timezone then my server.

How can I apply and change the server's NSDate to return current device NSDate for my calculation will be exact for every time zone.

I simply need a function that will get my server NSDate with my server's timezone (gmt+2) and will return the correct device NSDate.

hope someone can help me on that

Server returns Ticks (running on c#) and manipulating to nsdate with this code

double tickFactor = 10000000;
double ticksDoubleValue = [ticks doubleValue];
double seconds = ((ticksDoubleValue - 621355968000000000)/ tickFactor);
NSDate *returnDate = [NSDate dateWithTimeIntervalSince1970:seconds];
return returnDate;

Upvotes: 0

Views: 85

Answers (1)

Avi
Avi

Reputation: 7552

The NSDate class stores an absolute time. To facilitate this, it represents time in UTC, which is time-zone-agnostic. However you create an NSDate, it is assumed the time is in UTC. Even when you use NSDateFormatter to "read" a date from a string, it's just doing the math on your behalf, before creating the NSDate.

If you have a time representation that includes a time zone offset, you need to account for that when you do the conversion. As mentioned above, given a proper format string, NSDateFormatter will do that for you. If your representation is numeric (typically number of seconds from some date), you need to add or subtract the time zone offset. Add if the offset is negative, subtract if it's positive.

To adjust a server date provided in the server's local time, adjust based on the server's time zone. For GMT+2, subtract 3600 * 2 (number of seconds per hour * offset). This gives the seconds in UTC. When you create the NSDate using `[NSDate dateWithTimeIntervalSince1970:]. it will be the expected time.

Upvotes: 1

Related Questions