iOS - Friendly NSDate format

前端 未结 9 2306
伪装坚强ぢ
伪装坚强ぢ 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:14

    There are about a million ways you could do this, but here's a quick one:

    NSString* hoursAgo = [NSString stringWithFormat:@"%.0lf hours ago", fabs([date timeIntervalSinceNow] / 3600.0)]
    

    Of course, this doesn't check that date is actually from the past, doesn't do anything but hours, etc. But, you probably get the idea.

    timeIntervalSinceNow returns how many seconds have passed since a given date, with positive numbers being a date in the future and negative numbers being a date in the past. So, we get how many seconds have passed, divide it by 3600 seconds in an hour to compute the hours that have passed, and then put its absolute value into the string "n hours ago".

提交回复
热议问题