PHP日期和时间

编程 · 2023-11-14 · 242 人浏览

microtime

返回当前时间戳以及微秒数。

<?php
function runtime($start = null, $end = null) {
    static $cache = [];
    if (is_null($start)) {
        return $cache;
    } elseif (is_null($end)) {
        return $cache[$start] = microtime(true);
    } else {
        $end = $cache[$end] ?? microtime(true);
        return round($end - $cache[$start], 3);
    }
}

runtime('for');
for ($i = 0; $i < 10000000; $i++) {
    $i++;
}
runtime('forEnd');
echo 'for循环用的时间:' . runtime('for', 'forEnd');

strtotime

将任何英文文本日期时间描述解析为时间戳。

<?php
echo date('Y-m-d H:i:s', strtotime("2020-01-01 01:01:01")), "\n";
echo date('Y-m-d H:i:s', strtotime("now")), "\n";
echo date('Y-m-d H:i:s', strtotime("+1 day")), "\n";
echo date('Y-m-d H:i:s', strtotime("+1 year +1 day")), "\n";

DateTime

<?php
$dt = new DateTime();
$dt2 = new DateTime('2023-11-11 11:11:11');
$interval = $dt->diff($dt2);
$format = '距离你的生日还有 %m个月%d天%h小时,共有%a天。';
echo $interval->format($format);

DateInterval

<?php
$dt = new DateTime();
$interval = new DateInterval('P2DT3H5M'); //2天3小时5分钟
echo $dt->format('Y-m-d H:i:s');
echo PHP_EOL;
// 增加
$dt->add($interval);
echo $dt->format('Y-m-d H:i:s');
echo PHP_EOL;
// 减少
$dt->sub($interval);
echo $dt->format('Y-m-d H:i:s');
PHP
Theme Jasmine by Kent Liao