程序中一般使用Unix时间戳来计算和保留时间,php中用来处理时间的函数有mktime()将时间转为Unix时间
;strtotime()将英文自然时间转为Unix时间;getdate()将Unix时间转为关联数组;date_default_timezone_set()设置时区;microtime()返回微秒时间,详细如下面代码:
<?php
//将时区设为北京时间,否则默认为格林威治时间(在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)) . "<br />";
echo mktime(1, 2, 3, 4, 5, 2012) . "<br />";
//strtotime()可以将英语自然语言描述的日期转换成时间戳
echo strtotime("now") . "<br />";
echo date("Y-m-d h:i:s", strtotime("now")) . "<br/>";
echo date("Y-m-d h:i:s", strtotime("yesterday")) . "<br/>";
echo date("Y-m-d h:i:s", strtotime("last sunday")) ."<br />";
//用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!" . "<br />";
//getdate()函数返回一个由时间戳组成的关联数组,参数是一个可选的unix时间戳,如果为空,就取当前系统时间
$time = mktime(1, 2, 3 , 4, 5, 2012);
$myDate = getdate($time);
print_r($myDate);
echo "<br />";
echo "$myDate[weekday], $myDate[month] $myDate[mday], $myDate[year]" . "<br />";
//Unix时间戳最小单位为秒,如果想精确到毫秒级,可以使用microtime()函数,该函数返回Unix时间戳和微秒数
$startTime = microtime(true);
echo "Start time : " . $startTime . "<br />";
$stopTime = microtime(true);
echo "Stop time : " . $stopTime . "<br />";
echo "time used : " . ($stopTime-$startTime) . "seconds<br/>";
?>
版权声明
本站文章、图片、视频等(除转载外),均采用知识共享署名 4.0 国际许可协议(CC BY-NC-SA 4.0),转载请注明出处、非商业性使用、并且以相同协议共享。
© 空空博客,本文链接:https://www.yeetrack.com/?p=77
近期评论