How to compare current date to previous date in iphone?

前端 未结 4 1645
夕颜
夕颜 2021-01-04 21:17

I would like to compare the current date with another date, and if that is date is earlier than the current date, then I should stop the next action. How can I do this?

4条回答
  •  盖世英雄少女心
    2021-01-04 21:52

    Some methods of NSDate class are:

    1. isEarlierThanDate. // using this method you can find out the date is previous or not..
    2. isLaterThanDate
    3. minutesAfterDate.
    4. minutesBeforeDate. etc..

    also see this link with many methods of NSDate in iPhone SDK..

    how-to-real-world-dates-with-the-iphone-sdk

    Update

    //Current Date
        NSDate *date = [NSDate date];
        NSDateFormatter *formatter = nil;
        formatter=[[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
    

    use this bellow method for convert NSString date to NSDate format just paste this method in your.m file

    - (NSDate *)convertStringToDate:(NSString *) date {
    NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    NSDate *nowDate = [[[NSDate alloc] init] autorelease];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    // NSLog(@"date============================>>>>>>>>>>>>>>> : %@", date);
    date = [date stringByReplacingOccurrencesOfString:@"+0000" withString:@""];
    nowDate = [formatter dateFromString:date];
    // NSLog(@"date============================>>>>>>>>>>>>>>> : %@", nowDate);
    return nowDate;
    }
    

    after that when you want to use it just use like bellow..

    NSDate *tempDate2 = [self convertStringToDate:yourStringDate];
    

    and then try to compare like this..

    if (tempDate2 > nowDate)
    

提交回复
热议问题