计算指定时间与当前的时间差 比如,3天前、10分钟前

计算指定时间与当前的时间差  比如,3天前、10分钟前(这个在项目中经常遇到,所以记录了下来)

以下是实现方法:

 

/**

 * 计算指定时间与当前的时间差

 * @param compareDate   某一指定时间 

 * @return 多少(秒or分or天or月or年)+前 (比如,3天前、10分钟前) 

 */

+(NSString *) compareCurrentTime:(NSDate*) compareDate

//                         

{

    NSTimeInterval  timeInterval = [compareDate timeIntervalSinceNow];

    timeInterval = -timeInterval;

    long temp = 0;

    NSString *result;

    if (timeInterval < 60) {

        result = [NSStringstringWithFormat:@"刚刚"];

    }

    else if((temp = timeInterval/60) <60){

       result = [NSStringstringWithFormat:@"%d分前",temp];

    }

    

    else if((temp = temp/60) <24){

        result = [NSStringstringWithFormat:@"%d小前",temp];

    }

     

    else if((temp = temp/24) <30){

        result = [NSStringstringWithFormat:@"%d天前",temp];

    }

    

    else if((temp = temp/30) <12){

        result = [NSStringstringWithFormat:@"%d月前",temp];

    }

    else{

        temp = temp/12;

        result = [NSStringstringWithFormat:@"%d年前",temp];

    }

    

    return  result;

}

以下是NSDate中的常用方法:

 

/**

     

     - (id)initWithTimeInterval:(NSTimeInterval)secs sinceDate:(NSDate *)refDate;

     初始化为以refDate为基准,然后过了secs秒的时间

     

     - (id)initWithTimeIntervalSinceNow:(NSTimeInterval)secs;

     初始化为以当前时间为基准,然后过了secs秒的时间

     

     

     - (NSTimeInterval)timeIntervalSinceDate:(NSDate *)refDate;

     以refDate为基准时间,返回实例保存的时间与refDate的时间间隔

     

     - (NSTimeInterval)timeIntervalSinceNow;

     以当前时间(Now)为基准时间,返回实例保存的时间与当前时间(Now)的时间间隔

     

     - (NSTimeInterval)timeIntervalSince1970;

     以1970/01/01 GMT为基准时间,返回实例保存的时间与1970/01/01 GMT的时间间隔

     

     - (NSTimeInterval)timeIntervalSinceReferenceDate;

     以2001/01/01 GMT为基准时间,返回实例保存的时间与2001/01/01 GMT的时间间隔

     

     

     + (NSTimeInterval)timeIntervalSinceReferenceDate;


       */

    

    

    //

    // - (NSTimeInterval)timeIntervalSinceNow;

//    以当前时间(Now)为基准时间,返回实例保存的时间与当前时间(Now)的时间间隔

  


posted on 2015-01-26 16:10  奋进的闹钟  阅读(656)  评论(0编辑  收藏  举报

导航