Need assistance regarding NSDateFormatter

怎甘沉沦 提交于 2020-01-07 09:28:55

问题


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.


回答1:


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



回答2:


here is your solution

you are passing string sdata in nsdate,rather pass nsdate object like this

     NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd-MM-yyyy"];
    NSDate *now = [[NSDate alloc] init];

    NSDate *last=[dateFormat stringFromDate:now];
    NSLog(@"last==%@",last);



回答3:


You will need to use NSCalender class to get year, month and date components. NSDate class will always be represented in GMT.

Use

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *date = [NSDate date];
[calendar components:(NSDayCalendarUnit | NSMonthCalendarUnit) fromDate:date];

Check this article too. Use properties to retrieve value from NSDate http://nshipster.com/nsdatecomponents/




回答4:


Here is the simple code

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString* reqDate = [dateFormatter stringFromDate:[[NSDate alloc] init]];
NSLog(@"reqDate: %@",reqDate);//reqDate: 30-10-2014


来源:https://stackoverflow.com/questions/26646455/need-assistance-regarding-nsdateformatter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!