php面试基础知识--时间函数
2019-05-15 本文已影响0人
沙蒿同学
- date() : string
格式化一个本地时间/日期
<?php
$timestamp = time(); //时间戳
date('Y-m-d H:i:s', $timestamp ); //返回当前时间,yyyy-mm-dd H:i:s格式
- time() : int
返回当前的 Unix 时间戳,(格林威治时间 1970 年 1 月 1 日 00:00:00)到当前时间的秒数
- strtotime() : int
将任何字符串的日期时间描述解析为 Unix 时间戳(string to time)
<?php
echo strtotime("now"), "\n"; //当前时间
echo strtotime("10 September 2000"), "\n";
echo strtotime("+1 day"), "\n"; //明天
echo strtotime("+1 week"), "\n"; //下星期
echo strtotime("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime("next Thursday"), "\n"; //下周三
echo strtotime("last Monday"), "\n"; //上周一
?>
- microtime() : mixed
返回当前 Unix 时间戳和微秒数,PHP没有直接返回毫秒的函数,要想获取当前时间毫秒,这里用微秒格式化一下生产微秒。
<?php
return sprintf('%.0f', microtime(true) * 1000); //true,microtime() 将返回一个浮点数
- 常见时间格式转换
<?php
//$time 时间戳
public checkTime($time)
{
$return_str = '';
$diff = $time - time();
switch ($diff) {
case $diff < 60:
$return_str = $diff.'秒前';
break;
case $diff >= 60 && $diff < 60 * 60:
$diff_i = round($diff/60).'分';
$diff_s = ($diff - ($diff_i * 60)) > 0 ? ($diff - ($diff_i * 60)) .'秒' : '';
$return_str = $diff_i.$diff_s.'前';
break;
case $diff >= 60 * 60 && $diff <= 24 * 60 * 60:
$return_str = round($diff/(60 * 60)).'小时前';
break;
case $diff <= 30 * 24 * 60 * 60:
$return_str = round($diff/(24 * 60 * 60)).'天前';
break;
default:
$return_str = date('Y'.'年'.'m'.'月'.'d'.'日', $time);
}
return $return_str;
}