Convert NSDate from GMT+0 (London) to User's TimeZone

ぐ巨炮叔叔 提交于 2019-12-11 17:47:44

问题


I have a NSString (date) retrieved from my MySQL database which is in GMT +000 (London) and its format is like this: 12/05/2011 5:21:29 PM.

I would like to know how I could convert it to the user's time zone so that if the user was in china for example, it would be that date in the chinese time zone.


回答1:


Use setTimeZone: on your input NSDateFormatter. (Internally, NSDates are time zone agnostic.)

E.g.:

// The default time zone for a formatter is the time zone of the user's locale
NSDateFormatter *localFormatter = [[NSDateFormatter alloc] init];
[localFormatter setDateStyle:NSDateFormatterShortStyle];
[localFormatter setTimeStyle:NSDateFormatterMediumStyle];

NSDateFormatter *gmtFormatter = [[NSDateFormatter alloc] init];
[gmtFormatter setDateFormat:@"MM/dd/yyyy h:mm:ss a"];
[gmtFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

NSDate *date = [gmtFormatter dateFromString:gmtDateString];
NSString *locallyFormattedDate = [localFormatter stringFromDate:date];

[localFormatter release];
[gmtFormatter release];

Although…I don't think this takes DST into account if the DST setting during the specified time is different than the current setting.




回答2:


Use initWithTimeInterval:sinceDate: to make a date object that adds/subtracts hours. It will be in seconds, so 3 hours ahead would be initWithTimeInterval:10800 sinceDate:(originalDate). The format that would be given if you called -description on that object would be given as (from Apple Documentation)

A string representation of the receiver in the international format YYYY-MM-DD HH:MM:SS ±HHMM, where ±HHMM represents the time zone offset in hours and minutes from GMT (for example, “2001-03-24 10:45:32 +0600”).

So it would include the time interval.

EDIT: Sorry I was using the wrong init method, that is the one you are looking for, initWithTimeInterval:sinceDate:. You make a new NSDate that adds or subtracts the number of seconds that the timezone is ahead/behind.



来源:https://stackoverflow.com/questions/6165247/convert-nsdate-from-gmt0-london-to-users-timezone

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