iOS - Friendly NSDate format

前端 未结 9 2353
伪装坚强ぢ
伪装坚强ぢ 2021-02-04 13:31

I need to display the date of posts in my app to the user, right now I do it in this format: \"Fri, 25 May\". How would I format an NSDate to read something like \"2 hours ago\"

9条回答
  •  青春惊慌失措
    2021-02-04 14:13

    Adding to the solution try this more simplified method

        NSDateComponents *today = [[NSCalendar currentCalendar] components:NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:passed toDate:[NSDate date] options:0];
        NSTimeInterval interval = [[NSDate date] timeIntervalSinceDate:date];
    
        if (interval < 60) timestampString = [NSString stringWithFormat:@"%d seconds ago" ,today.second];
        else if (interval < 60 * 60) timestampString = [NSString stringWithFormat:@"%d minutes ago" ,today.minute];
        else if (interval < 60 * 60 * 24) timestampString = [NSString stringWithFormat:@"%d hours ago" ,today.hour];
        else timestampString = [NSString stringWithFormat:@"%d days ago" ,today.day];
    

提交回复
热议问题