日期输出为刚刚、几分钟前、几小时前、日期

本文介绍了一种在iOS应用中将特定格式的时间字符串转换为相对时间描述的方法,例如“刚刚”、“几分钟前”等,并根据时间差返回不同的描述格式。

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

-(NSString *)setTimeDisplayType
{
    NSString *strDate = @"2012-08-07 09:59:01";
    NSDateFormatter *formater = [[NSDateFormatter alloc] init];
    formater.dateFormat = @"yyyy-MM-dd HH:mm:ss";
    NSDate *constDate = [formater dateFromString:strDate];
    [formater release];
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDate *now = [NSDate date];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    
    comps = [calendar components:unitFlags fromDate:constDate toDate:now options:0];
    [calendar release];
    
    NSInteger months = [comps month];
    NSInteger days = [comps day];
    NSInteger hours = [comps hour];
    NSInteger mins = [comps minute];
    //NSInteger secs = [comps second];
    
    NSDateFormatter *dateForm = [[NSDateFormatter alloc] init];
    dateForm.dateFormat = @"MM-dd HH:mm:ss";
    
    if (months == 0)
    {
        if (days == 0)
        {
            if (hours == 0)
            {
                if (mins == 0)
                {
                    return @"刚刚";
                }
                else
                {
                    return [NSString stringWithFormat:@"%d分钟前",mins];
                }
            }
            else
            {
                return [NSString stringWithFormat:@"%d小时前",hours];
            }
        }
        else
        {
            return [NSString stringWithFormat:@"%@",[dateForm stringFromDate:now]];
            
        }
    }
    else
    {
        return [NSString stringWithFormat:@"%@",[dateForm stringFromDate:now]];
    }
    [dateForm release];
    [comps release];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值