php 本周开始时间和结束时间;本月开始时间结束时间;上月开始时间结束时间
封面图
•
2025-10-10
•
PHP
151
0
0
0
在 PHP 中,你可以使用 `DateTime` 类来获取 **本周、本月、上月** 的开始时间和结束时间。下面是一个完整的示例代码,展示如何获取这些时间范围: --- ### ✅ 获取本周的开始和结束时间(周一到周日) ```php <?php $now = new DateTime(); // 设置为本周一(假设一周从周一开始) $weekStart = clone $now; $weekStart->modify('this week Monday'); // 设置为本周日 $weekEnd = clone $now; $weekEnd->modify('this week Sunday'); echo "本周开始时间: " . $weekStart->format('Y-m-d H:i:s') . "\n"; echo "本周结束时间: " . $weekEnd->format('Y-m-d H:i:s') . "\n"; ``` --- ### ✅ 获取本月的开始和结束时间 ```php <?php $now = new DateTime(); // 本月第一天 $monthStart = clone $now; $monthStart->setDate($now->format('Y'), $now->format('m'), 1); // 本月最后一天 $monthEnd = clone $now; $monthEnd->setDate($now->format('Y'), $now->format('m'), $monthEnd->format('t')); echo "本月开始时间: " . $monthStart->format('Y-m-d H:i:s') . "\n"; echo "本月结束时间: " . $monthEnd->format('Y-m-d H:i:s') . "\n"; ``` --- ### ✅ 获取上个月的开始和结束时间 ```php <?php $now = new DateTime(); // 上个月的第一天 $lastMonthStart = clone $now; $lastMonthStart->modify('-1 month'); $lastMonthStart->setDate($lastMonthStart->format('Y'), $lastMonthStart->format('m'), 1); // 上个月的最后一天 $lastMonthEnd = clone $now; $lastMonthEnd->modify('-1 month'); $lastMonthEnd->setDate($lastMonthEnd->format('Y'), $lastMonthEnd->format('m'), $lastMonthEnd->format('t')); echo "上月开始时间: " . $lastMonthStart->format('Y-m-d H:i:s') . "\n"; echo "上月结束时间: " . $lastMonthEnd->format('Y-m-d H:i:s') . "\n"; ``` --- ### 📌 注意事项: - `DateTime::modify()` 可以用来调整日期。 - `format('t')` 可以获取某个月的总天数。 - 如果你希望一周从周日开始,可以使用 `Sunday` 而不是 `Monday`。 --- ### 🔄 示例输出(假设今天是 2025-04-05): ``` 本周开始时间: 2025-04-07 00:00:00 本周结束时间: 2025-04-13 23:59:59 本月开始时间: 2025-04-01 00:00:00 本月结束时间: 2025-04-30 23:59:59 上月开始时间: 2025-03-01 00:00:00 上月结束时间: 2025-03-31 23:59:59 ``` --- 如果你需要将时间格式改为 `timestamp` 或其他格式,也可以通过 `getTimestamp()` 方法获取时间戳。 如需帮助封装成函数或类,请告诉我!
上一篇:
php中使用preg_replace函数匹配图片并加上链接的方法
下一篇:
PHP strcmp() 函数
标题录入,一次不能超过6条
返回顶部
留言
留言
评论