2

I am sending some requests on a webserver that replies me time and date like this:

"at 18:58 of 05/08/2012"

I can figure out how to get the time and the date in 2 NSStrings(18:58, 05/08/2012). Note that the server's time zone is +00:00. What I want to accomplish is to present this time based on user's location. So for example if the reply from server is 23:30 at 05/08/2012 and the user's time zone is +2:00 I want to present him 1:30 at 06/08/2012. Any ideas?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
BlackM
  • 3,927
  • 8
  • 39
  • 69

2 Answers2

10

You should do it the following way:

1) First, create an NSDateFormatter to get the NSDate sent from the server:

NSDateFormatter *serverFormatter = [[NSDateFormatter alloc] init];
[serverFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[serverFormatter setDateFormat:@"'at 'HH:mm' of 'dd/MM/yyyy"];

From Apple docs: note with the Unicode format string format, you should enclose literal text in the format string between apostrophes ('').

2) Convert the string (consider it is defined as theString) to a NSDate:

NSDate *theDate = [serverFormatter dateFromString:theString];

3) Create an NSDateFormatter to convert theDate to the user:

NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init];
[userFormatter setDateFormat:@"HH:mm dd/MM/yyyy"];
[userFormatter setTimeZone:[NSTimeZone localTimeZone]];

3) Get the string from the userFormatter:

NSString *dateConverted = [userFormatter stringFromDate:theDate];
Natan R.
  • 5,141
  • 1
  • 31
  • 48
  • I did exactly what you wrote here and I get "HH:mm dd/MM/yyyy" as result – BlackM Aug 18 '13 at 11:42
  • Oh, I added by mistake a ' in the line `[userFormatter setDateFormat:....]` . Edited and corrected, get this line again. – Natan R. Aug 18 '13 at 12:03
  • Ok now is showing exactly the same time. What am I missing here? – BlackM Aug 18 '13 at 16:19
  • With or without "at"? Check the last edit, where I added `[serverFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];` to the first part – Natan R. Aug 18 '13 at 16:26
  • I am using UTC so I did "[serverFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:3600]]; " and now it's working fine. Thank you for your great answer. So this should be working fine on each timezone right? – BlackM Aug 18 '13 at 16:34
  • In my opinion, this way it won't work. The server formatter should be set to GMT, and the user formatter should be set to the time zone of the user via localTimeZone. To test, you can change the time zone in the device/simulator settings and check if it's working. Please upvote if you liked the answer :) – Natan R. Aug 18 '13 at 17:59
0

instead of getting absolute time from server get timestamp from server and convert that in to date at the client side, for this you didn't have to change the timezone also.

Manish Agrawal
  • 10,958
  • 6
  • 44
  • 76