简体   繁体   中英

How to compare system date with UIDatePicker's date in iOS?

Through my App users can order specific food item in restaurants..The thing is that if a user want to order a specific product he can give atleast 6 hrs time for the restaurant to deliver the product.For example you are the user,right now time is 12:00pm..In the app,user can select the timings of DELIVERY through UIDatepicker.Here if user selects the time before 06:00pm,one alert view will generate with message "please give 6hrs time for your order".Here i have to compare system time and UIDatepickers time.I found one method,,but it is not useful.

if ([self.datePicker.date compare:currentdate] == NSOrderedDescending){
   NSLog(@"Descending");
}

Please help me...Thanks in advance

use this

if ([[NSDate date] isEqualToDate: currentdate) {
NSLog(@"currentDate is equal to currentdate"); 
}

Either you can compare the selected time by

NSDate *date1 = [NSDate date];
NSDate *date2 = datePicker.date;

NSTimeInterval elapsed = [date1 timeIntervalSinceDate:date2];

Also you can set minimum time of date picker after 6 hours

NSDate *mydate = [NSDate date];
NSTimeInterval secondsInSixHours = 6 * 60 * 60;
NSDate *dateSixHoursAhead = [mydate dateByAddingTimeInterval:secondsInSixHours];
[datePicker setMinimumDate:dateSixHoursAhead];

您实际上正在寻找时差,这是代码:

NSLog(@"please give %@fhrs time for your order",[self.datePicker.date timeIntervalSinceDate:[NSDate date]]);

Use this method. The best way of doing comparison between two dates:

- (void)pickerDateIsSmallerThanCurrent:(NSDate *)checkDate
    {
        NSDate* enddate = checkDate;
        NSDate* currentdate = [NSDate date];
        NSTimeInterval distanceBetweenDates = [enddate timeIntervalSinceDate:currentdate];
        double secondsInMinute = 60;
        NSInteger secondsBetweenDates = distanceBetweenDates / secondsInMinute;

        if (secondsBetweenDates == 0)
             //both dates are equal
        else if (secondsBetweenDates < 0)
             //selected date is smaller than current date
        else
            //selected date is greater than current date
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM