find total number of days between two dates in iph

2019-03-27 12:34发布

I would like to find total number of days between two dates.

e.g. today is 01-01-2011(DD-MM-YYYY) and second date is (25-03-2011), how would I find the total number of days?

NSDate *currentdate=[NSDate date];
NSLog(@"curretdate is ==%@",currentdate);
NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
[tempFormatter1 setDateFormat:@"dd-mm-YYYY hh:mm:ss"];
NSDate *toDate = [tempFormatter1 dateFromString:@"20-04-2011 09:00:00"];

NSLog(@"toDate ==%@",toDate);

9条回答
Animai°情兽
2楼-- · 2019-03-27 12:37

A simpler way of doing it is:

// This just sets up the two dates you want to compare
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"dd-MM-yyyy"];
NSDate *startDate = [formatter dateFromString:@"01-01-2011"];
NSDate *endDate = [formatter dateFromString:@"25-03-2011"];

// This performs the difference calculation
unsigned flags = NSDayCalendarUnit;
NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];

// This just logs your output
NSLog(@"Start Date, %@", startDate);
NSLog(@"End Date, %@", endDate);
NSLog(@"%ld", [difference day]);

And the results are:

Start Date, 2011-01-01 00:00:00 +0000

End Date, 2011-03-25 00:00:00 +0000

83

Trying to use and manipulate seconds for calculating time differences is a bad idea. There are a whole load of classes and methods provided by Cocoa for Calendrical calculations and you should use them as much as possible.

查看更多
再贱就再见
3楼-- · 2019-03-27 12:43

Please try this. Hope it helps you...

NSDateFormatter *df=[[NSDateFormatter alloc] init];
// Set the date format according to your needs
[df setDateFormat:@"MM/dd/YYYY hh:mm a"]; //for 12 hour format
//[df setDateFormat:@"MM/dd/YYYY HH:mm "]  // for 24 hour format
NSDate *date1 = [df dateFromString:firstDateString];
NSDate *date2 = [df dateFromString:secondDatestring];
NSLog(@"%@f is the time difference",[date2 timeIntervalSinceDate:date1]);
[df release];
查看更多
干净又极端
4楼-- · 2019-03-27 12:44
//write this code in .h file
{
    NSDate *startDate,*EndDate;
    NSDateFormatter *Date_Formatter;
}
//write this code in .h file`enter code here`
- (void)viewDidLoad
{
    [super viewDidLoad];
    Date_Formatter =[[NSDateFormatter alloc]init];
    [Date_Formatter setDateFormat:@"dd-MM-yyyy"];

    UIToolbar *numbertoolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    numbertoolbar.barStyle = UIBarStyleBlackTranslucent;
    numbertoolbar.items = [NSArray arrayWithObjects:[[UIBarButtonItem alloc]initWithTitle:@"Next"
    style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad)],nil];
    [numbertoolbar sizeToFit];

    Txt_Start_Date.inputAccessoryView = numbertoolbar;
    [Txt_Start_Date setInputView:Picker_Date];
    Txt_End_Date.inputAccessoryView = numbertoolbar;
    [Txt_End_Date setInputView:Picker_Date];
    [Picker_Date addTarget:self action:@selector(updateTextfield:) forControlEvents:UIControlEventValueChanged];
    // Do any additional setup after loading the view, typically from a nib.
}
-(void)doneWithNumberPad
{

    if ([Txt_Start_Date isFirstResponder])
    {
        [Txt_Start_Date resignFirstResponder];
        [Txt_End_Date becomeFirstResponder];
    }
    else if([Txt_End_Date isFirstResponder])
    {
        [Txt_End_Date resignFirstResponder];

        startDate =[Date_Formatter dateFromString:Txt_Start_Date.text];
        EndDate =[Date_Formatter dateFromString:Txt_End_Date.text];
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *components = [calendar components:NSDayCalendarUnit fromDate:startDate toDate:EndDate options:0];
        Lab_Total_Days.text =[NSString stringWithFormat:@"%ld",components.day];
    }

}
查看更多
劳资没心,怎么记你
5楼-- · 2019-03-27 12:45

In your date Format tor u set wrong it`s be dd-MM-yyyy HH:mm:ss . may be that was the problem.. u get wrong date and not get answer i send litte bit code for get day diffrence.

  NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init]autorelease];
 [tempFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
  NSDate *startdate = [tempFormatter dateFromString:@"15-01-2011 09:00:00"];
  NSLog(@"startdate ==%@",startdate);

  NSDateFormatter *tempFormatter1 = [[[NSDateFormatter alloc]init]autorelease];
  [tempFormatter1 setDateFormat:@"dd-MM-yyyy HH:mm:ss"];
  NSDate *toDate = [tempFormatter1 dateFromString:@"20-01-2011 09:00:00"];
  NSLog(@"toDate ==%@",toDate);

   int i = [startdate timeIntervalSince1970];
   int j = [toDate timeIntervalSince1970];

   double X = j-i;

   int days=(int)((double)X/(3600.0*24.00));
   NSLog(@"Total Days Between::%d",days);

Edit 1:

we can find date difference using following function :

-(int)dateDiffrenceFromDate:(NSString *)date1 second:(NSString *)date2 {
    // Manage Date Formation same for both dates
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"dd-MM-yyyy"];
    NSDate *startDate = [formatter dateFromString:date1];
    NSDate *endDate = [formatter dateFromString:date2];


    unsigned flags = NSDayCalendarUnit;
    NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];

    int dayDiff = [difference day];

    return dayDiff;
}

from Abizern`s ans. find more infromation for NSDateComponent here.

查看更多
别忘想泡老子
6楼-- · 2019-03-27 12:50
NSDate *dateA;
NSDate *dateB;

NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *components = [calendar components:NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit
                                           fromDate:dateA
                                             toDate:dateB
                                            options:0];

NSLog(@"Difference in date components: %i/%i/%i", components.day, components.month, components.year);
查看更多
叼着烟拽天下
7楼-- · 2019-03-27 12:52

//try it

if((![txtFromDate.text isEqualToString:@""]) && (![txtToDate.text isEqualToString:@""]))
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"MM/dd/yyyy"];
        NSDate *startDate = [formatter dateFromString:txtFromDate.text];
        NSDate *endDate = [formatter dateFromString:txtToDate.text];
        unsigned flags = NSDayCalendarUnit;
        NSDateComponents *difference = [[NSCalendar currentCalendar] components:flags fromDate:startDate toDate:endDate options:0];

        int dayDiff = [difference day];

        lblNoOfDays.text =[NSString stringWithFormat:@"%d",dayDiff];
    }
查看更多
登录 后发表回答