问题描述
我从我的 MySQL 数据库中检索到了一个 NSString(日期),其格式为 GMT +000(伦敦),其格式如下:12/05/2011 5:21:29 PM.
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.
推荐答案
在您的输入 NSDateFormatter
上使用 setTimeZone:
.(在内部,NSDate
s 与时区无关.)
Use setTimeZone:
on your input NSDateFormatter
. (Internally, NSDate
s are time zone agnostic.)
例如:
// 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.
这篇关于将 NSDate 从 GMT+0(伦敦)转换为用户的时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!