** 其月份的结束时间都是其起始时间减去1s **,明白了这一点对月份的时间段处理就变得非常简单,保证不会有bug问题
今天我们来说说PHP的时间段的获取。
时间段其主要是获取某个时间段的起始时间点和结束时间点就ok了,这里要注意的是时间格式。我自己在写项目中比较常用的时间格式“Y-m-d H:i:s”,其次起始时间一般是从’00:00:00‘,结束时间为’23:59:59‘。
我们先来看看本月、上月、本周、上周的时间段是如何表示的。
以下是我封装的函数:
/**
* PHP时间段获取
* @param type currentMonth、lastMonth、currentWeek、lastWeek
*/
function dateRange($type) {
$res = [];
$currentMonthFirst = date('Y-m-01', time()) . ' 00:00:00';
$nextMonthFirst = date('Y-m-01', strtotime('+1 month')) . '00:00:00';
$lastMonthFirst = date('Y-m-01', strtotime('-1 month')) . ' 00:00:00';
switch ($type) {
case 'currentMonth' :
$res['start'] = $currentMonthFirst;
$res['end'] = date('Y-m-d H:i:s', strtotime($nextMonthFirst)-1);
break;
case 'lastMonth':
$res['start'] = $lastMonthFirst;
$res['end'] = date('Y-m-d H:i:s', strtotime($currentMonthFirst)-1);
break;
case 'currentWeek':
$res['start'] = date('Y-m-d', strtotime('this week')) . '00:00:00';
$res['end'] = date('Y-m-d w', strtotime('next week -1 day')) . '23:59:59';
break;
case 'lastWeek':
$res['start'] = date('Y-m-d', strtotime('last week')) . '00:00:00';
$res['end'] = date('Y-m-d w', strtotime('this week -1 day')) . '23:59:59';
break;
}
return res;
}
以上的函数用法非常简单,也很清晰。其结果返回的是一个数组。数值key为’start‘起始时间,’end‘表示结束时间。 比如你想获得上个月时间:
$lastMonth = dateRange('lastMonth');
$start = $lastMonth['start'];
$end = $lastMonth['end'];
//如果执行此段代码的时间是1月份.
//那么这里的start为2017-12-01 00:00:00
//end:为2017-12-31 23:59:59
//就是上月的时间。
说说代码,主要是strtotime()和date()两个函数的应用。上面看似非常简单的代码其实还是有写技巧的, 其月份的结束时间都是其起始时间减去1s ,明白了这一点对月份的时间段处理就变得非常简单,保证不会有bug问题。
这样的时间段是在统计中是非常常见的。对于常见的大家可以将它封装放到自己的代码库中方便自己日后写项目中调用,来提高自己日后的开发效率。
除特别注明外,本站所有文章均为作者原创。 或分享自己的编程经验,或探讨工作中的问题,或聊以人生趣事。 转载请注明出处来自 https://www.qiusuoweb.com/115.html
运营天数
总访问量
文章数量
-
-
-
交流群:157451741
新浪微博:草莽兴
发布评论