ios – 查找iphone中两个日期之间的总天数

我想找到两个日期之间的总天数.

例如今天是01-01-2011(DD-MM-YYYY),第二个日期是(25-03-2011),我怎样才能找到总天数?

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);

解决方法

在你的日期格式你设置错误它是dd-MM-yyyy HH:mm:ss.可能是那个问题..你得到错误的日期而没有得到答案我发送litte位代码获得一天的差异.
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);

编辑1:

我们可以使用以下功能找到日期差异:

-(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;
}

来自Abizern的ans.找到更多NSDateComponent here.的信息

相关文章

当我们远离最新的 iOS 16 更新版本时,我们听到了困扰 Apple...
欧版/美版 特别说一下,美版选错了 可能会永久丧失4G,不过只...
一般在接外包的时候, 通常第三方需要安装你的app进行测...
前言为了让更多的人永远记住12月13日,各大厂都在这一天将应...