PHP时间处理函数

时间:2022-05-11 14:42:36
<?php
//mktime() 将日期和时间转换为unix时间戳
//time() 获取当前时间的unix时间戳
echo date("Y-m-d",mktime(0,0,0,12,31,2013))."<br>";

//实例:通过计算两个unix时间戳的差,来计算一个用户的年龄

$year = 1991; //假设用户的出生日期是1991.07.16
$month = 07;
$day = 16;
$brithday = mktime(0,0,0,$month,$day,$year); //将用户的出生日期转换为unix时间戳
$nowdate = time(); //获得当前时间的unix时间戳
$ageunix = $nowdate - $brithday; //获取时间戳的差值
$age = floor($ageunix / (60*60*24*365)); //时间戳的差值除以每年的秒数即是用户的实际年龄
echo "该用户的年龄是".$age."<br><br>";
//date_default_timezone_set()  设置时区
//getdate() 确定当前的时间
//gettimeofday() 获取某一天中的具体时间
//date_sunrise() 某天的日出时间
//date_sunset() 某天的日落时间
//date() 格式化一个本地时间和日期
//microtime() 返回当前UNIX时间戳和微秒数
//下面的类通过获得两次函数的执行时间,来计算程序的执行时间
class Timer{
private $startTime;
private $stopTime;
function __construct(){
$this->startTime = 0;
$this->stopTime = 0;
}
function start(){
$this->startTime = microtime(true);
}
function stop(){
$this->stopTime = microtime(true);
}
function spent(){
return round(($this->startTime - $this->stopTime),4);
}
}
$timer = new Timer();
$timer->start();
usleep(1000);
$timer->stop();
echo "执行脚本用时<b>".$timer->spent()."</b>秒";
?>