Home >Backend Development >PHP Problem >How to calculate how many days ago in php

How to calculate how many days ago in php

藏色散人
藏色散人Original
2021-07-13 09:58:192084browse

How to calculate the time a few days ago in php: First create a PHP sample file; then calculate the time a few days ago through the "function time_tran($time){...}" method.

How to calculate how many days ago in php

The operating environment of this article: Windows 7 system, PHP version 7.1, DELL G3 computer

PHP calculates minutes ago, hours ago, and what time Days ago, a few months ago, a few years ago

/*
* $time 需要格式化的时间戳
* return 格式化时间
*/
 
function time_tran($time){
 
$text = '';
 
if(!$time){return $text;}
 
$current = time();
 
$t = $current - $time;
 
$retArr = array('刚刚','秒前','分钟前','小时前','天前','月前','年前');
 
switch($t){
 
case $t < 0://时间大于当前时间,返回格式化时间
 
$text = date(&#39;Y-m-d&#39;,$time);
 
break;
 
case $t == 0://刚刚
 
$text = $retArr[0];
 
break;
 
case $t < 60:// 几秒前
 
$text = $t.$retArr[1];
 
break;
 
case $t < 3600://几分钟前
 
$text = floor($t / 60).$retArr[2];
 
break;
 
case $t < 86400://几小时前
 
$text = floor($t / 3600).$retArr[3];
 
break;
 
case $t < 2592000: //几天前
 
$text = floor($t / 86400).$retArr[4];
 
break;
 
case $t < 31536000: //几个月前
 
$text = floor($t / 2592000).$retArr[5];
 
break;
 
default : //几年前
 
$text = floor($t / 31536000).$retArr[6];
 
}
 
return $text;
 
}

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to calculate how many days ago in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn