17

I have a little function that shows latest activity, it grab timestamp in unix format from the db, and then it echo out with this line:

 date("G:i:s j M -Y", $last_access)

Now i would like to replace the date (j M -Y) to Yesterday, and Today if the latest activity was within today, and same goes with Yesterday.

How can i do this?

hakre
  • 193,403
  • 52
  • 435
  • 836
Karem
  • 17,615
  • 72
  • 178
  • 278
  • 1
    Do you have any code that you've written so far? – Tim McNamara Aug 10 '10 at 23:29
  • Can you please try to be more precise? I haven't understood what you mean by Yesterday and Today... frankly ;-) – maraspin Aug 10 '10 at 23:36
  • 2
    It's tomorrow you need to worry about, not yesterday or today, clearing away all those cobwebs and the sorrow, just knowing it's a day away and all that. –  Aug 10 '10 at 23:42

12 Answers12

44

I would find the timestap for last midnight and the one before it, if $last_access is between the two timestamps, then display yesterday, anything greater than last midnight's timestamp would be today...

I believe that would be the quicker than doing date arithmetic.

Actually, I just tested this code and it seems to work great:

<?php
    if ($last_access >= strtotime("today"))
        echo "Today";
    else if ($last_access >= strtotime("yesterday"))
        echo "Yesterday";
?>
Hameed
  • 2,227
  • 1
  • 21
  • 31
15
function get_day_name($timestamp) {

    $date = date('d/m/Y', $timestamp);

    if($date == date('d/m/Y')) {
      $date = 'Today';
    } 
    else if($date == date('d/m/Y',now() - (24 * 60 * 60))) {
      $date = 'Yesterday';
    }
    return $date;
}
print date('G:i:s', $last_access).' '.get_day_name($last_access);
Shahzad Barkati
  • 2,532
  • 6
  • 25
  • 33
Benbob
  • 13,876
  • 18
  • 79
  • 114
11

You have to compare day with day, secondes comparaison are totally wrong :

If we are today morning, that means yesterday night is today (by minus 24h) ^^

Here a method I use for Kinoulink ( a french startup ) :

public function formatDateAgo($value)
{
    $time = strtotime($value);
    $d = new \DateTime($value);

    $weekDays = ['Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi', 'Dimanche'];
    $months = ['Janvier', 'Février', 'Mars', 'Avril',' Mai', 'Juin', 'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Décembre'];

    if ($time > strtotime('-2 minutes'))
    {
        return 'Il y a quelques secondes';
    }
    elseif ($time > strtotime('-30 minutes'))
    {
        return 'Il y a ' . floor((strtotime('now') - $time)/60) . ' min';
    }
    elseif ($time > strtotime('today'))
    {
        return $d->format('G:i');
    }
    elseif ($time > strtotime('yesterday'))
    {
        return 'Hier, ' . $d->format('G:i');
    }
    elseif ($time > strtotime('this week'))
    {
        return $weekDays[$d->format('N') - 1] . ', ' . $d->format('G:i');
    }
    else
    {
        return $d->format('j') . ' ' . $months[$d->format('n') - 1] . ', ' . $d->format('G:i');
    }
}
Thomas Decaux
  • 21,738
  • 2
  • 113
  • 124
4

I enhanced Thomas Decaux answer to come up with this

function formatTimeString($timeStamp) {
$str_time = date("Y-m-d H:i:sP", $timeStamp);
$time = strtotime($str_time);
$d = new DateTime($str_time);

$weekDays = ['Mon', 'Tue', 'Wed', 'Thur', 'Fri', 'Sat', 'Sun'];
$months = ['Jan', 'Feb', 'Mar', 'Apr', ' May', 'Jun', 'Jul', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];

if ($time > strtotime('-2 minutes')) {
  return 'Just now';
} elseif ($time > strtotime('-59 minutes')) {
  $min_diff = floor((strtotime('now') - $time) / 60);
  return $min_diff . ' min' . (($min_diff != 1) ? "s" : "") . ' ago';
} elseif ($time > strtotime('-23 hours')) {
  $hour_diff = floor((strtotime('now') - $time) / (60 * 60));
  return $hour_diff . ' hour' . (($hour_diff != 1) ? "s" : "") . ' ago';
} elseif ($time > strtotime('today')) {
  return $d->format('G:i');
} elseif ($time > strtotime('yesterday')) {
  return 'Yesterday at ' . $d->format('G:i');
} elseif ($time > strtotime('this week')) {
  return $weekDays[$d->format('N') - 1] . ' at ' . $d->format('G:i');
} else {
  return $d->format('j') . ' ' . $months[$d->format('n') - 1] .
  (($d->format('Y') != date("Y")) ? $d->format(' Y') : "") .
  ' at ' . $d->format('G:i');
}

}

It takes in the time stamp as the argument, it adds the year of the time if it was from a different year, etc...

Joshua
  • 818
  • 11
  • 12
3
echo date("Y:m:d",strtotime("today"));
echo date("Y:m:d",strtotime("yesterday")); 
dılo sürücü
  • 3,821
  • 1
  • 26
  • 28
  • Hi! While this may be a solution to the question, code only answers are generally discouraged on SO. Please take some time to edit your response with an explanation as to why this is a solution as it will help OP and future visitors of the site. – d_kennetz Apr 11 '19 at 19:23
2

If you are going down the road as suggested above, with unix timestamps for today / yesterday, have a look at strtotime, one of the greatest inventions of the 20th (or 21st?) century:

echo strtotime("yesterday"); // midnight
1281391200

echo strtotime("today"); // midnight
1281477600

echo strtotime("today, 1:30");
1281483000
mvds
  • 45,755
  • 8
  • 102
  • 111
1
something like:

$now = time();

$last_midnight = $now - ($now % (24*60*60));

if ($last_access >= $last_midnight)
{
 print "Today";
}    
elseif ($last_access >= ($last_midnight-(24*60*60))
{
 Print "Yesterday";
}
tcrosley
  • 779
  • 3
  • 13
  • @mvds: I didn't know you could use relative strings in strtotime. Nice. Some gotchas re PHP4 vs PHP5 though. – tcrosley Aug 11 '10 at 00:17
  • I actually use it in some web based search service to allow the user to enter a sliding window: e.g. from "two months ago" to "today". – mvds Aug 11 '10 at 00:25
1

we can get Date Difference using diff method of DateTime class.

<?php
    $date1 = new DateTime("2022-07-26");
    $date2 = new DateTime("2022-07-27");
    
    $days = $date2->diff($date1)->format('%r%d');
    
    if($days === 0) {
        return 'Today';
    } else if($days === "-1") {
        return 'yesterday';
    }else {
        return $days . ' days later';
    }
?>

for more details see

  1. this answer
  2. PHP doc example
  3. How to calculate the difference between two dates
Harsh Patel
  • 1,032
  • 6
  • 21
0

here's working function

    function minus_one_day($date){
      $date2 = formatDate4db($date);
      $date1 = str_replace('-', '/', $date2);
      $yesterday = date('Y-m-d',strtotime($date1 . "-1 days"));
      return $yesterday; }

hope work for you...

0
$today=new DateTime('now');
$yesterday=date($today,strtotime("-1 day"));
dılo sürücü
  • 3,821
  • 1
  • 26
  • 28
  • Can you explain that further? Most other answers need some kind of comparison to print either `Yesterday` or `Today`, but your code is missing it - are you sure this solves the given problem? – Nico Haase Apr 11 '19 at 15:03
  • $today=new DateTime('now'); $yesterday=date($today,strtotime("-1 day")); maybe not wokıing ... – dılo sürücü Apr 11 '19 at 15:07
  • That looks like the same code you've posted in your answer. But how does it print something? How does it print either the exact string `Yesterday` or `Today`? – Nico Haase Apr 11 '19 at 15:08
0
date('d.m.Y',strtotime("-1 days"));
asega
  • 33
  • 8
  • This does not provide an answer to the question. Once you have sufficient [reputation](https://stackoverflow.com/help/whats-reputation) you will be able to [comment on any post](https://stackoverflow.com/help/privileges/comment); instead, [provide answers that don't require clarification from the asker](https://meta.stackexchange.com/questions/214173/why-do-i-need-50-reputation-to-comment-what-can-i-do-instead). - [From Review](/review/late-answers/32105175) – Monnomcjo Jun 30 '22 at 06:44
0

Persian type:

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'سال',
        'm' => 'ماه',
        'w' => 'هفته',
        'd' => 'روز',
        'h' => 'ساعت',
        'i' => 'دقیقه',
        's' => 'ثانیه',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? ' روز' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' قبل' : 'اکنون';
}
user19195635
  • 119
  • 6