Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Date transformer with json #87

Open
Jo-Developer opened this issue Jun 2, 2016 · 2 comments
Open

Date transformer with json #87

Jo-Developer opened this issue Jun 2, 2016 · 2 comments

Comments

@Jo-Developer
Copy link

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

@Voley
Copy link

Voley commented Jun 3, 2016

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
Copy link
Author

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)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants