Jump to content

PHP datetime Ago Function?


glassfish

Recommended Posts

Granularity determines the smallest interval you are interested in.

 

If an event occurred 3 days 5 hours 12 minutes 25 seconds ago would you want to show that, or would it be

  • 3 days ago
  • 3 days 5 hours ago
  • 3 days 5 hours 12 minutes ago

You might just want 3 days, but what if the event was only 5 hours 12 minutes 25 seconds ago, what then?

  • 5 hours ago?
  • today?

 

Have a look at DateTime (particulary DateTime::diff() )  and DateInterval classes.

Link to comment
Share on other sites

You can go Barad's route and craft one up, but if you need a good quick one:

 

https://github.com/jimmiw/php-time-ago

  0 <-> 29 secs                                                             # => less than a minute
  30 secs <-> 1 min, 29 secs                                                # => 1 minute
  1 min, 30 secs <-> 44 mins, 29 secs                                       # => [2..44] minutes
  44 mins, 30 secs <-> 89 mins, 29 secs                                     # => about 1 hour
  89 mins, 29 secs <-> 23 hrs, 59 mins, 29 secs                             # => about [2..24] hours
  23 hrs, 59 mins, 29 secs <-> 47 hrs, 59 mins, 29 secs                     # => 1 day
  47 hrs, 59 mins, 29 secs <-> 29 days, 23 hrs, 59 mins, 29 secs            # => [2..29] days
  29 days, 23 hrs, 59 mins, 30 secs <-> 59 days, 23 hrs, 59 mins, 29 secs   # => about 1 month
  59 days, 23 hrs, 59 mins, 30 secs <-> 1 yr minus 1 sec                    # => [2..12] months
  1 yr <-> 2 yrs minus 1 secs                                               # => about 1 year
  2 yrs <-> max time or date                                                # => over [2..X] years

Here is a more lightweight and simpler approach:

 

http://codeforgeek.com/2014/10/time-ago-implementation-php/

Edited by Monkuar
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.