欢迎访问宙启技术站
智能推送

使用PHP日期和时间函数:格式化、计算等

发布时间:2023-07-03 10:08:02

PHP提供了一些内置的日期和时间函数,用于格式化、计算等操作。下面是一些常用的函数和使用示例:

1. date()函数:用于格式化日期和时间。

$date = date('Y-m-d'); // 2022-01-01
$time = date('H:i:s'); // 12:00:00
$datetime = date('Y-m-d H:i:s'); // 2022-01-01 12:00:00

2. strtotime()函数:将时间字符串转换为时间戳。

$timestamp = strtotime('2022-01-01'); // 1640995200

3. time()函数:获取当前时间的时间戳。

$timestamp = time(); // 1640995200

4. mktime()函数:创建一个指定日期时间的时间戳。

$timestamp = mktime(12, 0, 0, 1, 1, 2022); // 1640995200

5. strtotime()和date()的结合使用:计算日期和时间的差值。

$start = strtotime('2022-01-01');
$end = strtotime('2022-01-10');
$days = ($end - $start) / (60 * 60 * 24); // 9

6. strtotime()和date()的结合使用:计算指定时间段后的日期和时间。

$start = strtotime('2022-01-01');
$days = 10;
$end = strtotime("+{$days} days", $start);
$result = date('Y-m-d', $end); // 2022-01-11

7. strtotime()和date()的结合使用:计算指定时间段前的日期和时间。

$end = strtotime('2022-01-11');
$days = 10;
$start = strtotime("-{$days} days", $end);
$result = date('Y-m-d', $start); // 2022-01-01

8. strtotime()和date()的结合使用:获取指定日期的星期几。

$date = '2022-01-01';
$weekday = date('l', strtotime($date)); // Saturday

9. strtotime()和date()的结合使用:获取当前周的周一和周日的日期。

$today = date('Y-m-d');
$monday = date('Y-m-d', strtotime("previous monday {$today}"));
$sunday = date('Y-m-d', strtotime("next sunday {$today}"));

这些函数提供了方便的日期和时间操作功能,在开发中使用起来非常方便。可以根据具体需求选择合适的函数并结合使用。