为什么strptime是4小时休息?

时间:2012-01-04 18:42:47

标签: objective-c nsstring nsdate strptime

如何使用strptime将"%Y-%m-%dT%H:%M:%SZ"格式化为正确的UNIX时间戳?

我尝试编写一个名为testDateWithString的方法(见下文)。

但是,它失败并显示错误消息:

'2011-12-27 08:35:46 +0000' should be equal to '2011-12-27 04:35:46 +0000'

我该如何解决这个问题?

#import <SenTestingKit/SenTestingKit.h>

@implementation NSDate (DateWithString)

+ (id)dateWithString:(NSString *)string {
    struct tm time; strptime([string UTF8String], "%Y-%m-%dT%H:%M:%SZ", &time);
    return [NSDate dateWithTimeIntervalSince1970:mktime(&time)];
}

@end

@interface NSDateTests : SenTestCase
@end

@implementation NSDateTests

- (void)testDateWithString {
    NSDate *parsedDate = [NSDate dateWithString:@"2011-12-27T04:35:46Z"];
    NSDate *actualDate = [NSDate dateWithTimeIntervalSince1970:1324960546];
    STAssertEqualObjects(parsedDate, actualDate, nil);
}

@end

1 个答案:

答案 0 :(得分:1)

mktime给你当地时间,而非GMT。

请查看此答案以获取更多详细信息:Converting Between Local Times and GMT/UTC in C/C++

相关问题