How to convert NSDate in to relative format as “Today”,“Yesterday”,“a week ago”,“a month ago”,“a year ago”?

前端 未结 16 2082
天命终不由人
天命终不由人 2020-11-28 22:08

I want to convert nsdate in to relative format like \"Today\",\"Yesterday\",\"a week ago\",\"a month ago\",\"a year ago\",\"date as it is\".

I have writ

16条回答
  •  一个人的身影
    2020-11-28 22:48

    You will need to work out this logic yourself. You will need to determine the number of days in between those two dates.

    Here is a relatively naive approach:

    + (NSString *) dateDifference:(NSDate *)date
    {
        const NSTimeInterval secondsPerDay = 60 * 60 * 24;
        NSTimeInterval diff = [date timeIntervalSinceNow] * -1.0;
    
        // if the difference is negative, then the given date/time is in the future
        // (because we multiplied by -1.0 to make it easier to follow later)
        if (diff < 0)
            return @"In the future";
    
        diff /= secondsPerDay; // get the number of days
    
        // if the difference is less than 1, the date occurred today, etc.
        if (diff < 1)
            return @"Today";
        else if (diff < 2)
            return @"Yesterday";
        else if (diff < 8)
            return @"Last week";
        else
            return [date description]; // use a date formatter if necessary
    }
    

    It is naive for a number of reasons:

    1. It doesn't take into account leap days
    2. It assumes there are 86400 seconds in a day (there is such a thing as leap seconds!)

    However, this should at least help you head in the right direction. Also, avoid using get in method names. Using get in a method name typically indicates that the caller must provide their own output buffer. Consider NSArray's method, getItems:range:, and NSString's method, getCharacters:range:.

提交回复
热议问题