matthewcheok / Realm-JSON

A concise Mantle-like way of working with Realm and JSON.
MIT License
661 stars 129 forks source link

Date transformer with json #87

Open Jo-Developer opened 8 years ago

Jo-Developer commented 8 years ago

Hai, how to transform date as string from incoming json object to Nsdate using Realm-Json

Voley commented 8 years ago

Use NSDateFormatter inside value transformer.

.h:

#import <Foundation/Foundation.h>

@interface EZHStringToDateValueTransformer : NSValueTransformer

@end

.m

#import "EZHStringToDateValueTransformer.h"

static NSDateFormatter *defaultFormatter;
static NSDateFormatter *shortFormatter;

@implementation EZHStringToDateValueTransformer

+ (void)load {
    if (!defaultFormatter) {
        defaultFormatter = [[NSDateFormatter alloc] init];
        defaultFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ss";
    }

    if (!shortFormatter) {
        shortFormatter = [[NSDateFormatter alloc] init];
        shortFormatter.dateFormat = @"yyyy-MM-dd";
    }
}

+ (Class)transformedValueClass {
    return [NSDate class];
}

+ (BOOL)allowsReverseTransformation {
    return NO;
}

- (id)transformedValue:(NSString *)value {

    if (![value isKindOfClass:[NSString class]]) {
        // value is Null, return current date.
        return nil;
    }

    if (value.length == 10) {
        return [shortFormatter dateFromString:value];
    }

    if (value.length > 19) {
        value = [value stringByPaddingToLength:19 withString:@"" startingAtIndex:18];
    }
    return [defaultFormatter dateFromString:value];
}

It has some extra code, but the idea is the same.

Inside your realm object create a new method with a name of a date field that you need to transform before assigning, like so:

+ (NSValueTransformer *)cancelledAtJSONTransformer {
    return [[EZHStringToDateValueTransformer alloc] init];
}

Replace cancelledAt with your field name.

Jo-Developer commented 8 years ago

hai , in my incoming json object date and time are in different field so i need to combine both and save as date in realm using batch saving method without iterating using for loop using Realm-Json . please help me . (reply in swift will be more helpful)