Open Jo-Developer opened 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.
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)
Hai, how to transform date as string from incoming json object to Nsdate using Realm-Json