iOS - 将时间和日期转换为用户时区

Bla*_*ckM 2 timezone ios

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

"at 18:58 of 05/08/2012"
Run Code Online (Sandbox Code Playgroud)

我可以弄清楚如何在2 NSStrings(18:58,05/08/2012)获得时间和日期.请注意,服务器的时区是+00:00.我想要完成的是根据用户的位置显示这个时间.因此,例如,如果从服务器的应答是23:30在05/08/2012和用户的时区为+2:00我想现在他在1:30 06/08/2012.有任何想法吗?

Nat*_* R. 10

您应该通过以下方式执行此操作:

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

NSDateFormatter *serverFormatter = [[NSDateFormatter alloc] init];
[serverFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[serverFormatter setDateFormat:@"'at 'HH:mm' of 'dd/MM/yyyy"];
Run Code Online (Sandbox Code Playgroud)

从Apple文档:请注意Unicode格式的字符串格式,您应该在撇号('')之间的格式字符串中包含文字文本.

2)将字符串(将其定义为theString)转换为NSDate:

NSDate *theDate = [serverFormatter dateFromString:theString];
Run Code Online (Sandbox Code Playgroud)

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

NSDateFormatter *userFormatter = [[NSDateFormatter alloc] init];
[userFormatter setDateFormat:@"HH:mm dd/MM/yyyy"];
[userFormatter setTimeZone:[NSTimeZone localTimeZone]];
Run Code Online (Sandbox Code Playgroud)

3)从userFormatter获取字符串:

NSString *dateConverted = [userFormatter stringFromDate:theDate];
Run Code Online (Sandbox Code Playgroud)