程序中一般使用Unix时间戳来计算和保留时间,php中用来处理时间的函数有mktime()将时间转为Unix时间
;strtotime()将英文自然时间转为Unix时间;getdate()将Unix时间转为关联数组;date_default_timezone_set()设置时区;microtime()返回微秒时间,详细如下面代码:
//将时区设为北京时间,否则默认为格林威治时间(在php.ini中可以修改),与北京时间相差8小时
date_default_timezone_set("PRC");//RPC为中国英文简称
//mktime()用于将日期和时间转化为Unix时间戳,后面的参数依次是小时、分钟、秒、月、日、年;留空则会默认去当前日期
echo date("Y-m-d h:i:s", mktime(1, 2, 3, 4, 5, 2012)) . "
";
echo mktime(1, 2, 3, 4, 5, 2012) . "
";
//strtotime()可以将英语自然语言描述的日期转换成时间戳
echo strtotime("now") . "
";
echo date("Y-m-d h:i:s", strtotime("now")) . "
";
echo date("Y-m-d h:i:s", strtotime("yesterday")) . "
";
echo date("Y-m-d h:i:s", strtotime("last sunday")) ."
";
//用Unix时间戳来计算时间差
$year = 1990;
$month = 1;
$day = 1;
$birthday = mktime(0, 0, 0, $month, $day, $year);
$now = time();
$ageUnix = $now - $birthday;
$age = floor($ageUnix / (365*24*60*60));
echo "You are " . $age . " years old!" . "
";
//getdate()函数返回一个由时间戳组成的关联数组,参数是一个可选的unix时间戳,如果为空,就取当前系统时间
$time = mktime(1, 2, 3 , 4, 5, 2012);
$myDate = getdate($time);
print_r($myDate);
echo "
";
echo "$myDate[weekday], $myDate[month] $myDate[mday], $myDate[year]" . "
";
//Unix时间戳最小单位为秒,如果想精确到毫秒级,可以使用microtime()函数,该函数返回Unix时间戳和微秒数
$startTime = microtime(true);
echo "Start time : " . $startTime . "
";
$stopTime = microtime(true);
echo "Stop time : " . $stopTime . "
";
echo "time used : " . ($stopTime-$startTime) . "seconds
";
?>