月初和月末的时间戳

php
2022-08-30 18:01:36

如何使用PHP获取任何月份的第一分钟和最后几分钟的时间戳?


答案 1

您可以使用 mktimedate

$first_minute = mktime(0, 0, 0, date("n"), 1);
$last_minute = mktime(23, 59, 59, date("n"), date("t"));

这是本月的情况。如果要在任何月份使用它,则可以相应地更改月份和日期参数。

如果你想为每个月生成它,你可以循环:

$times  = array();
for($month = 1; $month <= 12; $month++) {
    $first_minute = mktime(0, 0, 0, $month, 1);
    $last_minute = mktime(23, 59, 59, $month, date('t', $first_minute));
    $times[$month] = array($first_minute, $last_minute);
}

演示


答案 2

使用 PHP 5.3,您可以

$oFirst = new DateTime('first day of this month');
$oLast  = new DateTime('last day of this month');
$oLast->setTime(23, 59, 59);

在 PHP 5.2 中

注意正如下面的注释中指出的那样,下一个示例仅在您先执行$oFirst部分时才有效。如果您在新的 DateTime 中添加 +1 个月,则结果将在当月的最后一天(从 php 5.5.9 开始)提前一个月。

$oToday = new DateTime();
$iTime  = mktime(0, 0, 0, $oToday->format('m'), 1, $oToday->format('Y'));
$oFirst = new DateTime(date('r', $iTime));

$oLast  = clone $oFirst;
$oLast->modify('+1 month');
$oLast->modify('-1 day');
$oLast->setTime(23, 59, 59);

推荐