Get the beginning and ending unix timestamp for a

2019-01-23 18:21发布

问题:

I want to find the timestamp for the first day in a month (say September 1 2010 and 0:00) and the last day in a month (say September 31 23:59).

回答1:

If you have those dates as strings you can simply use strtotime(), if you have only partial information you can use mktime().

However, September only has 30 days ;)

Example:

$month = 9;
$year  = 2010;

$first = mktime(0,0,0,$month,1,$year);
echo date('r', $first);

$last = mktime(23,59,00,$month+1,0,$year);
echo date('r', $last);


回答2:

If you are using PHP 5.3 (don't try this with 5.2, date parser works differently there) you could to the speaking:

<?php

$date = "2010-05-10 00:00:00";

$x = new DateTime($date);

$x->modify("last day of this month");
$x->modify("last second");

echo $x->format("Y-m-d H:i:s");
// 2010-05-30 23:59:59
$timestamp = $x->getTimestamp();


回答3:

Maybe it can be done simpler but you get the idea:

<?php

$start = mktime(0, 0, 1, $month, 1, $year);
$end   = mktime(23, 59, 00, $month, date('t', $month), $year);

?>