开始和月末的时间戳

时间:2011-01-15 23:09:14

标签: php

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

7 个答案:

答案 0 :(得分:44)

您可以使用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);
}

DEMO

答案 1 :(得分:14)

使用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中

注意 AllThecode在下面的评论中指出,如果您执行$oFirst部分,则下一个示例有效第一。如果将+1 month添加到new DateTime,结果将在该月的最后一天提前一个月(从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);

答案 2 :(得分:3)

使用mktime生成时间戳,从小时/月/日/ ...值和cal_days_in_month获取一个月内的天数:

$month = 1; $year = 2011;
$firstMinute = mktime(0, 0, 0, $month, 1, $year);
$days = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$lastMinute = mktime(23, 59, 0, $month, $days, $year);

答案 3 :(得分:3)

我认为更好

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

是:

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

答案 4 :(得分:2)

这需要PHP&gt; 5.2并需要调整“分钟”部分

$year = ...;  // this is your year
$month = ...; // this is your month
$month = ($month < 10 ? '0' . $month : $month);
$start = new DateTime($year . '-' . $month . '-01 00:00:00');
$end = $start->modify('+1 month -1 day -1 minute'); //perhaps this need 3 "->modify"
echo $start->format('U');
echo $end->format('U');

(未经测试)

参考:http://www.php.net/manual/en/class.datetime.php

答案 5 :(得分:0)

$date = new \DateTime('now');//Current time
$date->modify("-1 month");//get last month
$startDate = $date->format('Y-m-01');
$endDate = $date->format('Y-m-t');

答案 6 :(得分:0)

最好的方法就是这样。

$ first_day = date('m-01-Y h:i:s',strtotime(“-1 months”));

$ last_day = date('m-t-Y h:i:s',strtotime(“-1 months”));

相关问题