/**
* 获取指定年月日的开始时间戳和结束时间戳(本地时间戳非GMT时间戳)
* [1] 指定年:获取指定年份第一天第一秒的时间戳和下一年第一天第一秒的时间戳
* [2] 指定年月:获取指定年月第一天第一秒的时间戳和下一月第一天第一秒时间戳
* [3] 指定年月日:获取指定年月日第一天第一秒的时间戳
* @param integer $year [年份]
* @param integer $month [月份]
* @param integer $day [日期]
* @return array('start' => '', 'end' => '')
*/
function getStartAndEndUnixTimestamp($year = 0, $month = 0, $day = 0)
{
if(empty($year))
{
$year = date("Y");
}
$start_year = $year;
$start_year_formated = str_pad(intval($start_year), 4, "0", STR_PAD_RIGHT);
$end_year = $start_year + 1;
$end_year_formated = str_pad(intval($end_year), 4, "0", STR_PAD_RIGHT);
if(empty($month))
{
//只设置了年份
$start_month_formated = '01';
$end_month_formated = '01';
$start_day_formated = '01';
$end_day_formated = '01';
}
else
{
$month > 12 || $month < 1 ? $month = 1 : $month = $month;
$start_month = $month;
$start_month_formated = sprintf("%02d", intval($start_month));
if(empty($day))
{
//只设置了年份和月份
$end_month = $start_month + 1;
if($end_month > 12)
{
$end_month = 1;
}
else
{
$end_year_formated = $start_year_formated;
}
$end_month_formated = sprintf("%02d", intval($end_month));
$start_day_formated = '01';
$end_day_formated = '01';
}
else
{
//设置了年份月份和日期
$startTimestamp = strtotime($start_year_formated.'-'.$start_month_formated.'-'.sprintf("%02d", intval($day))." 00:00:00");
$endTimestamp = $startTimestamp + 24 * 3600 - 1;
return array('start' => $startTimestamp, 'end' => $endTimestamp);
}
}
$startTimestamp = strtotime($start_year_formated.'-'.$start_month_formated.'-'.$start_day_formated." 00:00:00");
$endTimestamp = strtotime($end_year_formated.'-'.$end_month_formated.'-'.$end_day_formated." 00:00:00") - 1;
return array('start' => $startTimestamp, 'end' => $endTimestamp);
}
使用例子如下所示:
<?php
echo "<pre>";
$result = getStartAndEndUnixTimestamp(2016);
$result1 = getStartAndEndUnixTimestamp(2016, 8);
$result2 = getStartAndEndUnixTimestamp(2016, 9, 30);
print_r($result);
print_r($result1);
print_r($result2);
?>
结果如下所示:
Array
(
[start] => 1451577600
[end] => 1483199999
)
Array
(
[start] => 1469980800
[end] => 1472659199
)
Array
(
[start] => 1475164800
[end] => 1475251199
)
以上就是PHP 获取指定年月日的开始和结束时间戳的全文介绍,希望对您学习和使用php有所帮助.
(adsbygoogle = window.adsbygoogle || []).push({});