dchohfi / KeyValueObjectMapping

Automatic KeyValue Object Mapping for Objective-C, parse JSON/plist/Dictionary automatically
http://dchohfi.com/
MIT License
600 stars 90 forks source link

Unix Timestamp Conversion Error #55

Open RuCray opened 10 years ago

RuCray commented 10 years ago

Unix Timestamp is in milliseconds while dateWithTimeIntervalSince1970: takes a NSTimeInterval in seconds. Currently the conversion is 1000x off.

ohnit commented 10 years ago

It depends on the implementation of the timestamp. It seems like some places use milliseconds, wikipedia says it should be seconds. I had the same problem. Here was my work around:

    DCParserConfiguration *config = [DCParserConfiguration configuration];

    DCCustomParser *dateParser = [[DCCustomParser alloc] initWithBlockParser:^id(NSDictionary *__weak dictionary, NSString *__weak attributeName, __weak Class destinationClass, __weak id value) {

        if (![value isKindOfClass:[NSNumber class]]) {
            return nil;
        }

        long timeStampInMilliseconds = [value longValue];

        /** Must convert timestamp from milliseconds to seconds */
        NSDate *date = [[NSDate alloc] initWithTimeIntervalSince1970:timeStampInMilliseconds/1000];

        return date;
    }
                                                                forAttributeName:@"_ivarName"
                                                          onDestinationClass:[YourClassName class]];

    [config addCustomParsersObject:dateParser];