php 获取上周日期_PHP获取本月、上月、本周、上周时间段

今天我们来说说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问题。

这样的时间段是在统计中是非常常见的。对于常见的大家可以将它封装放到自己的代码库中方便自己日后写项目中调用,来提高自己日后的开发效率。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值