iOS 根据时间戳计算聊天列表的时间(上午/下午)

本文介绍了一种将时间戳转换为更易读的时间格式的方法,如上午10:00、昨天14:00或3月15日15:00。通过使用NSDate和NSCalendar,代码可以判断消息发送的具体日期并将其格式化为相对时间。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

把时间戳转成聊天时间(上午 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];
    
}

 

转载于:https://www.cnblogs.com/xujiahui/p/8521999.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值