Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Convert Date to Messages Such as Yesterday at 2:00pm - Reverse strtotime

I am trying to build a function that takes a timestamp and generates "relative" string based date, possibly a reverse strtotime!

Yesterday at 2pm
Yesterday at 3:15pm
Earlier Today at 9am
Today at 12pm
Today at 12:45pm
Tomorrow at 5pm
Monday at 9pm
Sunday at 12:55am
All dates older than a week:
Thu 7th Jul

I currently have the below code, and was wondering how to improve it? It doens't seem very efficient and is missing some features. What would you add?

  static public function timestampRelativeString($timestamp, $rounding=900) {
    if(!self::isValidTimeStamp($timestamp))
      return "Invalid Timestamp";

    //Round to (default) 15 mins
    $timestamp = floor($timestamp/$rounding)*$rounding;

    //Today
    if($timestamp<mktime(0, 0, 0, date("m"), date("d")-1, date("y")))
      return date("D jS M", $timestamp);
    elseif($timestamp<mktime(23, 59, 59, date("m"), date("d")-1, date("y")))
      return "Today at ".date("G:i", $timestamp);
    elseif($timestamp<time()))
      return "Earlier today at ".date("G:i", $timestamp);
    elseif($timestamp<mktime(23, 59, 59, date("m"), date("d"), date("y")))
      return "Today at ".date("G:i", $timestamp);
    elseif($timestamp<mktime(23, 59, 59, date("m"), date("d")+1, date("y"))) //Tomorrow
      return "Tomorrow at ".date("G:i", $timestamp);
    elseif($timestamp<mktime(23, 59, 59, date("m"), date("d")+7, date("y"))) //Next Week
      return "On ".date("l", $timestamp)." at ".date("G:i", $timestamp);
    else 
      return date("D jS M", $timestamp);
  }

Does anyone know of a script that already does this? Or very similar?

Many thanks for your time,

like image 648
Pez Cuckow Avatar asked Oct 27 '25 08:10

Pez Cuckow


1 Answers

This has many names including nicetime and PrettyDate. The best way to do it is to output the actual time from PHP in a div/span with an ID or identifying class, and then post-process client side with javascript (which can then update the time as the user sits on the page).

Anyway, WRT to your question, I'd look at the prettydate processing classes out there, which are like (or exactly) the ones you see on Facebook, Twitter etc.. even if you do it in PHP you can at match the functionality.

like image 77
Rudu Avatar answered Oct 29 '25 21:10

Rudu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!