iPhone: Convert date string to a relative time stamp

后端 未结 11 1153
醉梦人生
醉梦人生 2020-11-27 09:30

I\'ve got a timestamp as a string like:

Thu, 21 May 09 19:10:09 -0700

and I\'d like to convert it to a relative time stamp like

11条回答
  •  不知归路
    2020-11-27 10:06

    Use the NSDate class:

    timeIntervalSinceDate
    

    returns the interval in seconds.

    Quick exercise to implement this in objective-c:

    1. Get time "now" NSDate
    2. Get the NSDate you wish to compare with
    3. Get the interval in seconds using timeIntervalSinceDate

    Then implement this pseudo code:

    if (x < 60) // x seconds ago
    
    else if( x/60 < 60) // floor(x/60) minutes ago
    
    else if (x/(60*60) < 24) // floor(x/(60*60) hours ago
    
    else if (x/(24*60*60) < 7) // floor(x(24*60*60) days ago
    

    and so on...

    then you need to decide whether a month is 30,31 or 28 days. Keep it simple - pick 30.

    There might be a better way, but its 2am and this is the first thing that came to mind...

提交回复
热议问题