Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I only want date like "29-10-2014" with no time so i did this

NSDateFormatter *df = [[NSDateFormatter alloc]init];
[df setDateFormat:@"dd-MM-yyyy"];
NSString *sDate = [df stringFromDate:date];

If I log the sDate I am getting perfect result. But I dont want NSString I want date object, to do that here what I did is

NSDate *theDate = [df dateFromString:sDate];

Now I am getting 2014-10-29 19:00:00 +0000 I only want 29-10-2014.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
134 views
Welcome To Ask or Share your Answers For Others

1 Answer

This is because -[NSDate description] returns you full formatted date.

You can swizzle NSDate's - (NSString *)description{} and return something that you want.
Note that this is a very bad practice

#import <objc/runtime.h>

@implementation NSDate (CustomDescription)

+ (void)load
{
    swizzleInstance(@selector(description),
                    @selector(description_m),
                    [UIViewController class],
                    [self class]);
}

static void swizzleInstance(SEL originalSl, SEL swizzledSl, Class originalCl, Class swizzledCl) {
    Method originalMethod = class_getInstanceMethod(originalCl, originalSl);
    Method swizzledMethod = class_getInstanceMethod(swizzledCl, swizzledSl);
    method_exchangeImplementations(originalMethod, swizzledMethod);
}

- (NSString *)description_m
{
    NSDateFormatter *df = [[NSDateFormatter alloc]init];
    [df setDateFormat:@"dd-MM-yyyy"];
    return [df stringFromDate:self];
}
@end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...