与NSDate和时区混淆

时间:2014-05-26 23:23:05

标签: ios nsdate

我的问题是我在运行时将时间戳转换为字符串并返回NSDate。该字符串被指定为GMT:0,但我住在GMT:-9。每次我尝试使用从字符串转换的日期并检测字符串中当前NSDateNSDate之间的间隔时,我得到一个错误的NSTimeInterval值。

以下是我的功能:

+(NSString*) timeStampString{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [dateFormatter setLocale:enUSPOSIXLocale];
    [dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    return [dateFormatter stringFromDate:[BBuyoUtilities timeStamp]];

}

+(NSDate*) timeStampToDate:(NSString*) timeStamp{

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSLocale *enUSPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
    [dateFormatter setLocale:enUSPOSIXLocale];
    [dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
    //This didnt work
    //[dateFormatter setTimeZone:[NSTimeZone systemTimeZone]];

    //Works with
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];

    NSDate* returnDate = [dateFormatter dateFromString:timeStamp];
    return returnDate;
}

0 个答案:

没有答案