根据业务需要,经常会根据指定日期获取某一范围的起止时间戳,其中都用到了php中strtotime函数,用于获取日期,时间戳,它还是非常强大,方便的。以下是我总结的部分业务下的获取起止时间戳的几种方法。
根据日期获取指定月份前的日期
public function getDateTime ($date = '2017-08-01', $month = 2) {
$time = date('Y-m-d', strtotime('-'.$month.' months', strtotime($date)));
return $time;
}
根据指定年月获取该月的起止时间戳。取这个起止时间时参考了一些其他的方法,按需要优化了一下。
public function monthBeginAndEnd ($year = '2017', $month = '8') {
$year = $year?$year:date('Y');
$month = $month?$month:date('m');
$month = sprintf('%02d', intval($month));
$year = str_pad(intval($year), 4, '0', STR_PAD_RIGHT);
$month >12 || $month < 1?$month = 1:$month = $month;
$beginTime = strtotime($year.'-'.$month.'-'.'01');
$beginTimeStr = date('Y-m-01', $beginTime);
$endTime = strtotime(date('Y-m-d 23:59:59', strtotime('$beginTimeStr +1 month -1 day')));
return array(
'beginTime' => $beginTime,
'endTime' => $endTime
);
}
获取指定日期近一周的起止时间戳。相对来说,这样取挺简单的,利用好php的一些函数,更优的方式也有的。
public function getWeekTime ($date = '2017-08-01') {
// 本周开始结束时间
$weekTime = date('w', strtotime($date));
$weekStartDate = date('Y-m-d', strtotime($date.'-'.($weekTime?($weekTime - 1):6).'days'));
$weekEndTime = strtotime($weekStartDate.'+ 6 days') + 86399;
$weekStartTime = strtotime($weekStartDate);
return array(
'beginTime' => $weekEndTime,
'endTime' => $weekStartTime
);
}