iOS - 将时间和日期转换为用户时区 [英] iOS - Converting time and date to user time zone

查看:353
本文介绍了iOS - 将时间和日期转换为用户时区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网络服务器上发送了一些请求,这些请求回复了我这样的时间和日期:

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

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

我可以弄清楚如何在2个NSStrings中获取时间和日期(18:58,05 / 08/2012)。
请注意,服务器的时区是+00:00。我想要完成的是根据用户的位置显示这个时间。因此,例如,如果服务器的回复是2012年5月5日23:30,用户的时区是+2:00,我想在2012年8月6日1:30给他。
有什么想法吗?

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?

推荐答案

你应该按照以下方式进行:

You should do it the following way:

1)首先,创建一个NSDateFormatter以获取从服务器发送的NSDate:

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

来自 Apple文档请注意Unicode格式的字符串格式,您应该将文字文本括在撇号('')之间的格式字符串中。

2)将字符串(认为它定义为 theString )转换为 NSDate

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

NSDate *theDate = [serverFormatter dateFromString:theString];

3)创建 NSDateFormatter theDate 转换为用户:

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)从userFormatter获取字符串:

NSString *dateConverted = [userFormatter stringFromDate:theDate];

这篇关于iOS - 将时间和日期转换为用户时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆