Format chat list time

Keywords: PHP

Recently, a function similar to customer service chat has been implemented.

But I don't know much about the time format that the list needs to be displayed

Therefore, refer to the time display logic of wechat chat list. I implemented a function myself

Specific rules:

  • If the time stamp to be formatted (T) > the time stamp in the morning of the same day, "xx:xx in the morning / afternoon" will be displayed
  • If t > yesterday morning time stamp, "yesterday" is displayed
  • "Week x" if t > this Monday's early morning time stamp
  • If t > last Monday's am time stamp, "last week x" is displayed
  • If T < the early morning time stamp of last Monday, determine whether the year t is in is the same as the current year
    • Same, display "x month x day"
    • Different, display "mm / DD / yyyy"

Specific code:

   /**
     * Format chat list time
     * @param $timestamp int time stamp
     * @return false|string
     */
    public static function formatChatListTime($timestamp){
        $today = strtotime('today');
        $yesterday = strtotime('yesterday');
        // This Monday
        $thisMonday = $today - ((date('w',time()) == 0 ? 7 : date('w',time()))-1)*24*3600;
        // Last Monday
        $lastMonday = $thisMonday - 7*24*3600;

        if ($timestamp > $today){
            $a = date('a', $timestamp);
            $t = date('h:i', $timestamp);
            if ($a == 'am'){
                $a = 'morning ';
            }else{
                $a = 'Afternoon ';
            }
            $result = $a.$t;
        }else if ($timestamp > $yesterday){
            $result = 'Yesterday';
        }else if ($timestamp > $thisMonday){
            $result = self::getWeekDesc($timestamp);
        }else if ($timestamp > $lastMonday){
            $result = 'upper' . self::getWeekDesc($timestamp);
        }else{
            if (date('Y', $timestamp) == date('Y', time())){
                $result = self::dateTimeFormat($timestamp, 'm month d day');
            }else{
                $result = self::dateTimeFormat($timestamp, 'Y year m month d day');
            }
        }
        return $result;
    }

/**
* Gets the day of the week for the specified time stamp - Chinese description
* @param int $timeStamp time stamp
* @return string
*/
public static function getWeekDesc($timeStamp){
if(intval($timeStamp) == 0){
return '';
}
$week = date('w', $timeStamp);
switch ($week){
case 0:
$desc = 'Sunday';
break;
case 1:
$desc = 'Monday';
break;
case 2:
$desc = 'Tuesday';
break;
case 3:
$desc = 'Wednesday';
break;
case 4:
$desc = 'Thursday';
break;
case 5:
$desc = 'Friday';
break;
case 6:
$desc = 'Saturday';
break;
default:
$desc = '';
break;
}
return $desc;
}
 

Posted by xcasio on Sat, 04 Jan 2020 11:25:41 -0800