Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Calculate number of days between two dates in iOS

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 484
    Comment on it

                       Number of days between two dates

    Here is a code given below for calculating the number of days between a specific date and current date i.e today’s date.

     

    So first of all code to fetch the current date or today’s date is given below followed by calculation of number of days between two dates.

    NSDate *currentDate = [NSDate date];// use to fetch the current date
            NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];//formatter is used to set the format of date you want
            [dateFormatter setDateFormat:@"YYYY.MM.dd];//here is the format which is required
            NSString *currentDateString = [dateFormatter stringFromDate:currentDate];// Here current date with the specific format is assigned to the NSString
            NSLog(@%@,currentDateString);// printing the string to check weather it display the current date or not


            
    Now we have to take an another date for taking out the number of days between two dates so here we will provide the date in the format of string by own.   

    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];//defining the format of date
           [formatter setDateFormat:@"YYYY.MM.dd"];
           NSDate *startDate = [formatter dateFromString:@2016.04.20];//Here we provide the start date
           NSDate *endDate = [formatter dateFromString:currentDateString];//Here we provide the end date i.e current date/todays date
           unsigned flags = NSCalendarUnitDay;//Performs the difference calculation between start and end date
           NSDateComponents *noOfDays = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];// calculating the difference
           NSLog(@"%ld", [noOfDays day]);//this will display the number of days between two given dates

     

    In this way we can calculate the number of days between two dates.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: