如何比较两个日期,返回天数

How can I compare two dates, return a number of days(如何比较两个日期,返回天数)
本文介绍了如何比较两个日期,返回天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何比较两个日期返回天数.例如:缺席 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];

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to stop UIBarButtonItem text from truncating?(如何阻止UIBarButtonItem文本被截断?)
java.lang.IllegalStateException: SimpleTypeImpl should not be created for error type(异常:不应为错误类型创建SimpleTypeImpl)
Android IllegalArgumentException: The tag for fragment_XXX is invalid. Received: layout-sw600dp/fragment_XXX_0(Android IlLegalArgumentException:Fragment_XXX的标签无效。收到:Layout-sw600dp/Fragment_XXX_0)
NSURLSessionTaskPriority seems to be ignored?(NSURLSessionTaskPriority似乎被忽略了?)
How to make dataWithEPSInsideRect vector rather than bitmap in vector format?(如何用EPSInside Rect将dataWithEPSInside Rect变成矢量而不是位图的矢量格式?)
HTTPS request using volley(使用 volley 的 HTTPS 请求)