2

如何使用 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
4

1 回答 1

1

mktime给你当地时间,而不是格林威治标准时间。

查看此答案以了解更多详细信息:在 C/C++ 中转换当地时间和 GMT/UTC

于 2012-01-15T22:21:36.373 回答