【发布时间】:2011-05-29 00:39:36
【问题描述】:
我从我的 MySQL 数据库中检索到一个 NSString(日期),该数据库位于 GMT +000(伦敦),其格式如下:12/05/2011 5:21:29 PM。
我想知道如何将其转换为用户的时区,例如,如果用户在中国,它将是中国时区的那个日期。
【问题讨论】:
标签: objective-c nsdate
我从我的 MySQL 数据库中检索到一个 NSString(日期),该数据库位于 GMT +000(伦敦),其格式如下:12/05/2011 5:21:29 PM。
我想知道如何将其转换为用户的时区,例如,如果用户在中国,它将是中国时区的那个日期。
【问题讨论】:
标签: objective-c nsdate
在您的输入 NSDateFormatter 上使用 setTimeZone:。 (在内部,NSDates 与时区无关。)
例如:
// 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];
虽然……如果指定时间内的 DST 设置与当前设置不同,我认为这不会考虑 DST。
【讨论】:
gmtDateString 未定义。
使用initWithTimeInterval:sinceDate: 创建一个添加/减去小时的日期对象。它将以秒为单位,因此提前 3 小时将是 initWithTimeInterval:10800 sinceDate:(originalDate)。如果您在该对象上调用 -description 将给出的格式将被给出为(来自 Apple 文档)
字符串表示 国际格式的接收器 YYYY-MM-DD HH:MM:SS ±HHMM,其中 ±HHMM 表示时区偏移量 从 GMT 开始的小时和分钟(对于 例如,“2001-03-24 10:45:32 +0600”)。
所以它会包括时间间隔。
编辑: 抱歉,我使用了错误的 init 方法,即您正在寻找的方法 initWithTimeInterval:sinceDate:。您创建一个新的 NSDate 来增加或减少时区领先/落后的秒数。
【讨论】:
-[NSTimeZone secondsFromGMT] 或-[NSTimeZone secondsFromGMTForDate:]。