iOS - Converting time and date to user time zone

≡放荡痞女 提交于 2019-12-30 05:23:05

问题


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?


回答1:


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];



回答2:


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.



来源:https://stackoverflow.com/questions/18298010/ios-converting-time-and-date-to-user-time-zone

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!