Comparing two dates with nsdate

天涯浪子 提交于 2019-12-02 20:04:40

问题


In my app I have to compare two times: current (which is 12:44) and given I tried:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm"];
NSDate *neededDate = [[NSDate alloc] init];
neededDate = [dateFormatter dateFromString:@"14:45"];
if ([neededDate compare:[NSDate date]] == NSOrderedAscending) {
NSLog(@"yes");
} else NSLog(@"no");
[neededDate release];
[dateFormatter release];

But any time I launch it, NSLog says "no". Please, suggest where I' m wrong. Thank you in advance.


回答1:


Because your neededDate will be equal to "1970/01/01 14:45".

You need to set correct year and date.

You can get current year, month and say, for example, using next approach:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:[NSDate date]];
NSLog(@"Current year: %d", components.year);
NSLog(@"Current month: %d", components.month);
NSLog(@"Current day: %d", components.day);



回答2:


I think the problem is here:

[dateFormatter setDateFormat:@"hh:mm"];

should be:

[dateFormatter setDateFormat:@"HH:mm"];

because now for "14:45" it returns (null) date

(this is additionally to previous answer :)




回答3:


it means that in your case, neededDate is always higher than the current date. this is probably because you store a 48 hour string in a 24 hour format. change the string to HH:mm

also, verify the value you store in neededDate.

here's a small example

NSDate *neededDate = [[NSDate date] dateByAddingTimeInterval:5];
    if ([neededDate compare:[NSDate date]] == NSOrderedAscending) {
        NSLog(@"asc");
    } else {
        NSLog(@"dec");
    }

in this case, dec will be printed.



来源:https://stackoverflow.com/questions/7901061/comparing-two-dates-with-nsdate

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