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.

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/

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.