NSString to NSDate conversion problem

℡╲_俬逩灬. 提交于 2019-11-29 15:50:12

问题


I am having a NSString object which I am converting to NSDate with help of NSDateFormatter. Now code works fine here with all the OS but it is creating different Output at client's add (USA region). Here is the code that I am using.

NSDateFormatter *formate = [[[NSDateFormatter alloc] init] autorelease];
[formate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSString *strConcat = @"2010-09-24 17:30:00";
NSDate *date = [formate dateFromString:strConcat];
NSLog(@"Output :%@",date);

Output at my end -------2010-09-24 17:30:00 - 0700 Output at Client end ----2010-09-25 00:30:00 GMT Can anyone please suggest where's the problem?

Thanks Pratik Goswami


回答1:


The only output difference I notice is the time is different. If you do not explicitly set the timeZone property of the formatter it will use the system's local timezone. If you expect the times to the be the exact same from you and your client:

[formate setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

That would insure the output is always GMT.




回答2:


You need to manually set the locale for the NSDateFormatter, so that all your users see the same formatted string. Otherwise, the formatter will use whatever locale is set for the device.




回答3:


Actually, it's working correctly. The two dates are equivalent, just that one is in the US/Mountain time zone and the other is in the Greenwich time zone. (5:30pm + 7 hours = 12:30 am)

What's the problem here?




回答4:


In iOS2.x and 3.x the description/datefromstring function returns: 2010-09-24 17:30:00 - 0700

in iOS 4.x it returns this: 2010-09-25 00:30:00 GMT

You could submit a bug to apple.



来源:https://stackoverflow.com/questions/3738363/nsstring-to-nsdate-conversion-problem

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