IT虾米网

ios 时间类转化为字符串详解

developer 2018年06月24日 手机开发 377 0
//  NSString* timeStr = [self stringWithDate: [NSDate dateWithTimeIntervalSince1970:userGifGrouptEntity.lastGiftSentTime / 1000]] 
 
- (NSString *)stringWithDate:(NSDate *)date  { 
 
    if (date == nil) 
 
        return @""; 
 
    NSDate *now = [NSDate date]; 
 
    NSTimeInterval time = [now timeIntervalSinceDate:date]; 
 
    NSCalendar* calendar = [NSCalendar currentCalendar]; 
 
    NSDateComponents *nowComponents = [calendar components:NSYearCalendarUnit | NSHourCalendarUnit fromDate:now]; 
 
    NSDateComponents *dateComponets = [calendar components:NSYearCalendarUnit fromDate:date]; 
 
     
 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
 
    [dateFormatter setCalendar: [NSCalendar autoupdatingCurrentCalendar]]; 
 
     
 
    if ([nowComponents year] != [dateComponets year]) { 
 
            [dateFormatter setDateFormat:@"MM-dd-yyyy"]; 
 
             return [dateFormatter stringFromDate:date]; 
 
    } 
 
      int nowHour = (int)[nowComponents hour]; 
 
    int days_ago = ((int)time + 3600*(24-nowHour))/(3600*24); 
 
     
 
    if (days_ago == 0){ 
 
        [dateFormatter setDateFormat:@"HH:mm"]; 
 
        return [dateFormatter stringFromDate:date]; 
 
    }else if(days_ago == 1) { 
 
                    return @"Yesterday"; 
 
          }else{ 
 
         
 
            [dateFormatter setDateFormat:@"MM-dd"]; 
 
      
 
        return [dateFormatter stringFromDate:date]; 
 
    } 
 
}

发布评论

分享到:

IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

IOS 8 使用系统自带导航详解
你是第一个吃螃蟹的人
发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。