如何比较两个日期,返回天数 [英] How can I compare two dates, return a number of days

查看:15
本文介绍了如何比较两个日期,返回天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何比较两个日期返回天数.例如:缺席 X 天的杯赛.看看我的代码.

how can I compare two dates return number of days. Ex: Missing X days of the Cup. look my code.

  NSDateFormatter *df = [[NSDateFormatter alloc]init];  
  [df setDateFormat:@"d MMMM,yyyy"];  
  NSDate *date1 = [df dateFromString:@"11-05-2010"];  
  NSDate *date2 = [df dateFromString:@"11-06-2010"];  
  NSTimeInterval interval = [date2 timeIntervalSinceDate:date1];  
  //int days = (int)interval / 30;  
  //int months = (interval - (months/30)) / 30;  
  NSString *timeDiff = [NSString stringWithFormat:@"%dMissing%d days of the Cup",date1,date2, fabs(interval)];  

  label.text = timeDiff; // output (Missing X days of the Cup)  

推荐答案

来自 苹果的例子,基本上用的是NSCalendar:

From Apple's example, basically use an NSCalendar:

NSDate * date1 = <however you initialize this>;
NSDate * date2 = <...>;

NSCalendar *gregorian = [[NSCalendar alloc]
                 initWithCalendarIdentifier:NSGregorianCalendar];

NSUInteger unitFlags = NSMonthCalendarUnit | NSDayCalendarUnit;

NSDateComponents *components = [gregorian components:unitFlags
                                          fromDate:date1
                                          toDate:date2 options:0];

NSInteger months = [components month];
NSInteger days = [components day];

这篇关于如何比较两个日期,返回天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆