<?php
// 获取指定月份的最后一天
// 方法一:使用 date 和 strtotime 函数
function getLastDayOfMonth($year, $month) {
// 使用 strtotime 函数生成指定年月的最后一天
return date("Y-m-t", strtotime("$year-$month-01"));
}
// 示例:获取2023年10月的最后一天
echo getLastDayOfMonth(2023, 10); // 输出:2023-10-31
// 方法二:使用 DateTime 类
function getLastDayOfMonthDateTime($year, $month) {
// 创建 DateTime 对象并设置为指定年月的第一天
$date = new DateTime("$year-$month-01");
// 修改日期为该月最后一天
$date->modify('last day of this month');
// 返回格式化后的日期字符串
return $date->format('Y-m-d');
}
// 示例:获取2023年10月的最后一天
echo getLastDayOfMonthDateTime(2023, 10); // 输出:2023-10-31
?>
date 和 strtotime 函数来获取指定年月的最后一天。strtotime 函数将字符串转换为时间戳,而 date 函数则根据时间戳返回格式化的日期字符串。"Y-m-t" 中的 t 表示该月的天数。DateTime 类,这是一个更面向对象的方式。我们首先创建一个 DateTime 对象,并将其设置为指定年月的第一天,然后使用 modify 方法将其修改为该月的最后一天,最后使用 format 方法返回格式化的日期字符串。这两种方法都可以方便地获取指定月份的最后一天。
上一篇:php 对象
下一篇:phpinfo函数的作用
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站