iOS 根據時間戳計算聊天列表的時間(上午/下午)


把時間戳轉成聊天時間(上午 10:00  、  昨天 14:00 、 3月15日 15:00)

+(NSString*)ChatingTime:(NSString *)timestring{
  
    
    int timestamp=  [timestring intValue];
    
    
        // 創建日歷對象
        NSCalendar *calendar = [NSCalendar currentCalendar];
        
        // 獲取當前時間
    NSDate *currentDate = [NSDate date];
        
        // 獲取當前時間的年、月、日。利用日歷
        NSDateComponents *components = [calendar components:NSCalendarUnitYear| NSCalendarUnitMonth|NSCalendarUnitDay fromDate:currentDate];
        NSInteger currentYear = components.year;
        NSInteger currentMonth = components.month;
        NSInteger currentDay = components.day;
    
        
        // 獲取消息發送時間的年、月、日
        NSDate *msgDate = [NSDate dateWithTimeIntervalSince1970:timestamp];
        components = [calendar components:NSCalendarUnitYear| NSCalendarUnitMonth|NSCalendarUnitDay|NSCalendarUnitHour fromDate:msgDate];
        CGFloat msgYear = components.year;
        CGFloat msgMonth = components.month;
        CGFloat msgDay = components.day;
        CGFloat msghours = components.hour;
        // 進行判斷
        NSDateFormatter *dateFmt = [[NSDateFormatter alloc] init];
        if (currentYear == msgYear && currentMonth == msgMonth && currentDay == msgDay) {
            //今天
            if (msghours<12) {
                dateFmt.dateFormat = @"上午 hh:mm";
            }else{
                dateFmt.dateFormat = @"下午 hh:mm";
            }
           
        }else if (currentYear == msgYear && currentMonth == msgMonth && currentDay-1 == msgDay ){
            //昨天
            dateFmt.dateFormat = @"昨天 HH:mm";
        }else{
            //昨天以前
            dateFmt.dateFormat = @"MM-dd HH:mm";
        }
        // 返回處理后的結果
        return [dateFmt stringFromDate:msgDate];
    
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM