在PHP中,可以使用日期函数 strtotime()
和 date()
来对比日期。
比较两个日期的方法,可以将两个日期都转化为时间戳格式,然后进行比较。
以下是一个例子,使用 strtotime()
将日期转化为时间戳,然后使用 date()
格式化输出:
$date1 = "2021-01-01";
$date2 = "2021-12-31";
$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);
if ($timestamp1 > $timestamp2) {
echo date("Y-m-d", $timestamp1) . "晚于" . date("Y-m-d", $timestamp2);
} elseif ($timestamp1 < $timestamp2) {
echo date("Y-m-d", $timestamp1) . "早于" . date("Y-m-d", $timestamp2);
} else {
echo date("Y-m-d", $timestamp1) . "等于" . date("Y-m-d", $timestamp2);
}
输出结果为:
2021-01-01 早于 2021-12-31
以上代码中,首先使用 strtotime()
将日期转化为时间戳格式,然后使用判断语句进行比较,最后使用 date()
函数输出结果。