標籤:ios
NSString *distanceTime = [self returnFromTheTimeOfToday:@"2016-09-29 01:45:10"];#pragma mark 預設一分鐘有60秒,一小時就60分鐘 一天有24小時,一周有7天,一個月有30天,一年有12個月 不考慮其他的如平年2月28天,閏月29天這些情況- (NSString *)returnFromTheTimeOfToday:(NSString *)timeStr{ //timeStr 字串格式->2016-09-29 01:45:10 NSDateFormatter *form = [[NSDateFormatter alloc] init]; //設定時區 form.locale = [NSLocale localeWithLocaleIdentifier:@"cn"]; form.dateFormat = @"yyyy-MM-dd HH:mm:ss"; NSDate *date = [form dateFromString:timeStr]; //得到當前的時間差 NSTimeInterval timeInterval = [date timeIntervalSinceNow]; timeInterval = -timeInterval; //然後進行時間的比較 if(timeInterval < 60) { return [NSString stringWithFormat:@"剛剛"]; } //分鐘 NSInteger minute = timeInterval / 60; if(minute < 60) { return [NSString stringWithFormat:@"%ld分鐘之前",minute]; } NSInteger hours = minute / 60; if(hours < 24) { return [NSString stringWithFormat:@"%ld小時之前",hours]; } NSInteger day = hours / 24; NSInteger month = day/30; NSInteger year = month/12; if(day <= 1) { form.dateFormat = @"HH:mm"; NSString *oldtime = [form stringFromDate:date]; return [NSString stringWithFormat:@"昨天 %@",oldtime]; } if(day < 7) { return [NSString stringWithFormat:@"%ld天之前",day]; } if((day/7)<4) { return [NSString stringWithFormat:@"%ld周之前",day/7]; } else if(month < 12) { return [NSString stringWithFormat:@"%ld月之前",month]; } else { form.dateFormat = @"yyyy-MM-dd HH:mm"; return [NSString stringWithFormat:@"%ld年之前",year]; } return nil; }
本文出自 “雪花飛落滿人間” 部落格,請務必保留此出處http://smengxiang.blog.51cto.com/11204872/1865680
IOS 距離現在的幾分,幾個小時,幾分鐘,幾天,幾周幾月,幾年