码迷,mamicode.com
首页 > 移动开发 > 详细

iOS日期的比较

时间:2015-05-06 15:14:05      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:ios日期比较   计算日期间隔   


  1.日期可以进行比较以确定大小或相等,也可以确定两个日期之间的时间间隔。两个日期的间隔时间差可以使用-timeIntervalSinceDate:方法来计算
  
  1. NSDate * now = [NSDate date];
  2.   NSDate * anHourAgo = [now dateByAddingTimeInterval:-60*60];
  3.   NSTimeInterVal timeBetween = [now timeIntervalSinceDate:anHourAgo];
  4.   NSLog(@”%f”,timeBetween);

  2.日期比较也可以使用-timeIntervalSinceNow方法获取和当前的时间间隔
  
  1. NSDate * anHourago = [NSDate dateWithTimeIntervalSinceNow;-60*60];
  2.   NSTimeInterval interval = [anHourAgo timeIntervalSinceNow];
  3.   NSLog(@”%f”,interval);


//创建日期格式化对象 
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init]; 
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"]; 
   
   
//创建了两个日期对象 
NSDate *date1=[dateFormatter dateFromString:@"2010-3-3 11:00"]; 
NSDate *date2=[dateFormatter dateFromString:@"2010-3-4 12:00"]; 
//NSDate *date=[NSDate date]; 
   //NSString *curdate=[dateFormatter stringFromDate:date]; 
   
//取两个日期对象的时间间隔: 
//这里的NSTimeInterval 并不是对象,是基本型,其实是double类型,是由c定义的:typedef double NSTimeInterval; 
NSTimeIntervaltime=[date2 timeIntervalSinceDate:date1]; 
   
int days=((int)time)/(3600*24); 
int hours=((int)time)%(3600*24)/3600; 
NSString *dateContent=[[NSString alloc] initWithFormat:@"%i天%i小时",days,hours];

  3.NSDate还提供了-laterDate、-earlierDate和compare方法来比较日期
  
  1. NSDate * now = [NSDate date];
  2.   NSDate * anHourAgo = [now dateByAddingTimeInterval:-60*60];
  3.   NSDate *result1 = [now laterDate:anHourAgo];
  4.   NSDate * result2 = [now earlierDate:anHourAgo];
  5.   NSComparisonResult result3 = [now compare:anHourAgo];


比较日期大小是任何编程语言都会经常遇到的问题,再iOS编程中,通常用NSDate对象来存储一个时间(包括日期和时间、时区),而且 NSDate类提供了compare方法来进行时间的比较,但有时不想那么精确的知道两个日期的大小(默认会比较到秒),可以用下面的实现方法:

+(int)compareOneDay:(NSDate *)oneDay withAnotherDay:(NSDate *)anotherDay
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"dd-MM-yyyy"];
    NSString *oneDayStr = [dateFormatter stringFromDate:oneDay];
    NSString *anotherDayStr = [dateFormatter stringFromDate:anotherDay];
    NSDate *dateA = [dateFormatter dateFromString:oneDayStr];
    NSDate *dateB = [dateFormatter dateFromString:anotherDayStr];
    NSComparisonResult result = [dateA compare:dateB];
    NSLog(@"date1 : %@, date2 : %@", oneDay, anotherDay);
    if (result == NSOrderedDescending) {
        //NSLog(@"Date1  is in the future");
        return 1;
    }
    else if (result == NSOrderedAscending){
        //NSLog(@"Date1 is in the past");
        return -1;
    }
    //NSLog(@"Both dates are the same");
    return 0;
             
}

iOS日期的比较

标签:ios日期比较   计算日期间隔   

原文地址:http://blog.csdn.net/huanghaiyan_123/article/details/45534817

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!