1. 获取当前日期和时间
使用 `date` 函数
`date` 函数可根据指定的格式返回当前日期和时间。
php
<?php
// 获取当前日期和时间,格式为 YYYY-MM-DD HH:MM:SS
$currentDateTime = date('Y-m-d H:i:s');
echo "当前日期和时间: ". $currentDateTime;
?>
使用 `DateTime` 类
`DateTime` 类是 PHP 中处理日期和时间的面向对象方式。
php
<?php
$now = new DateTime();
$currentDateTime = $now->format('Y-m-d H:i:s');
echo "当前日期和时间: ". $currentDateTime;
?>
2. 格式化日期和时间
`date` 函数格式化
`date` 函数支持多种格式选项,以下是一些常用的格式示例:
php
<?php
// 格式化为 2025年04月28日 12:30:00
$formattedDate = date('Y年m月d日 H:i:s');
echo $formattedDate;
?>
`DateTime` 类格式化
php
<?php
$date = new DateTime();
// 格式化为 28 Apr 2025, 12:30:00
$formattedDate = $date->format('d M Y, H:i:s');
echo $formattedDate;
?>
3. 日期和时间的加减操作
使用 `strtotime` 函数
`strtotime` 函数可将字符串转换为 Unix 时间戳,结合 `date` 函数可进行日期和时间的加减操作。
php
<?php
// 获取当前时间戳
$currentTimestamp = time();
// 加一天
$nextDayTimestamp = strtotime('+1 day', $currentTimestamp);
$nextDay = date('Y-m-d', $nextDayTimestamp);
echo "明天的日期: ". $nextDay;
?>
使用 `DateTime` 类
php
<?php
$date = new DateTime();
// 加一天
$date->modify('+1 day');
$nextDay = $date->format('Y-m-d');
echo "明天的日期: ". $nextDay;
?>
4. 计算日期差
使用 `DateTime` 类的 `diff` 方法
php
<?php
$startDate = new DateTime('2025-01-01');
$endDate = new DateTime('2025-04-28');
$interval = $startDate->diff($endDate);
echo "两个日期相差 ". $interval->days. " 天。";
?>
5. 验证日期和时间
使用 `checkdate` 函数
`checkdate` 函数用于验证日期的有效性。
php
<?php
$year = 2025;
$month = 4;
$day = 28;
if (checkdate($month, $day, $year)) {
echo "日期有效。";
} else {
echo "日期无效。";
}
?>
6. 将字符串转换为日期对象
使用 `DateTime` 类的构造函数
php
<?php
$dateString = '2025-04-28';
$date = new DateTime($dateString);
echo $date->format('Y年m月d日');
?>
7. 获取特定日期的信息
使用 `DateTime` 类的方法
php
<?php
$date = new DateTime('2025-04-28');
// 获取星期几
$weekday = $date->format('l');
echo "2025年04月28日是 ". $weekday;
?>
通过上述方法,你可以在 PHP 中灵活地处理日期和时间,满足不同的业务需求。