ma11hew28
ma11hew28

Reputation: 126477

Why is strptime is 4 hours off?

How do I use strptime to format "%Y-%m-%dT%H:%M:%SZ" into the correct UNIX timestamp?

I tried writing a method called testDateWithString (below).

But, it fails with error message:

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

How can I fix this?

#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

Upvotes: 2

Views: 924

Answers (1)

StilesCrisis
StilesCrisis

Reputation: 16300

mktime is giving you local time, not GMT.

Take a look at this answer for more details: Converting Between Local Times and GMT/UTC in C/C++

Upvotes: 1

Related Questions