How to get number of days between two dates objective-c [duplicate]

别等时光非礼了梦想. 提交于 2019-12-18 17:33:10

问题


I'm trying to make a label that says how many days left till event. I want to calculate the difference between todays date and the events date. I'm using this code and its giving me -4600. It works fine till I use todays date.

NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-dd"];
    NSDate *startDate = [NSDate date];
    NSDate *endDate = [f dateFromString:end];
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
                                                        fromDate:startDate
                                                          toDate:endDate
                                                         options:0];
    return components.day;
return components.day;

回答1:


By default [NSDate date] return date in like 2013-08-06 08:50:25 +0000 and you have set your formatter to yyyy-MM-dd this, so you have to convert your startDate to yyyy-MM-dd this form..

Try this

NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-ddHH:mm:ss ZZZ"];
    NSDate *startDate = [NSDate date];
    NSLog(@"%@",startDate);
    NSDate *endDate = [f dateFromString:end];
    NSLog(@"%@",endDate);


    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit
                                                        fromDate:startDate
                                                          toDate:endDate
                                                         options:0];
    return components.day; 


来源:https://stackoverflow.com/questions/18075183/how-to-get-number-of-days-between-two-dates-objective-c

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