Home >Backend Development >PHP Tutorial >PHP date processing function (calculate time difference, convert timestamp date)_PHP tutorial
PHP tutorial: Convert timestamp to common date format and calculate time difference: the default return type is "minutes"
function trans_time($timestamp){
if($timestamp < 1) echo 'Invalid unix timestamp';
else return date("y-m-d h:i:s",$timestamp);
}
//Get ip
function get_ip() {
If ($_server["http_x_forwarded_for"])
$ip = $_server["http_x_forwarded_for"];
else if ($_server["http_client_ip"])
$ip = $_server["http_client_ip"];
else if ($_server["remote_addr"])
$ip = $_server["remote_addr"];
else if (getenv("http_x_forwarded_for"))
$ip = getenv("http_x_forwarded_for");
else if (getenv("http_client_ip"))
$ip = getenv("http_client_ip");
else if (getenv("remote_addr"))
$ip = getenv("remote_addr");
else
$ip = "unknown";
Return $ip;
}
//Calculate time difference: the default return type is "minutes"
//$old_time can only be a timestamp, $return_type is h for hours, s for seconds
function timelag($old_time,$return_type='m'){
if($old_time < 1){
echo 'Invalid unix timestamp';
}else{
switch($return_type){
case 'h':
$type = 3600; break;
case 'm':
$type = 60; break;
case 's':
$type = 1; break;
case '':
$type = 60; break;
}
$dif = round( (time()-$old_time)/$type ) ;
Return $dif;
}
}