PHP得到最近一周和某月\某年的实际天数Date(t)\Date(z)
- 4952
- PHP
- 39
- super_dodo
- 2016/12/08
最近有一个接口的需求需要统计最近一周的相关的数据(如下图),也需要统计日均数据(因为月份是可以随意切换的,所以也就需要得到每个月有多少天的数据)。此处我写了一个简单的方法用于公共调用,当然有更好的方法。

温馨提示 Date('t',$time); //PHP日期函数得到某个月的真实天数
/**
* 用于获取最近一周的日期列表
* 用于计算每个月的天数(本月的话截止到今天2016-12-08)
*/
class DodoDate{
//得到最近7天的日期(由小到大) 2016-12-02 #你可以用循环的
public function getWeekDate(){
$data[] = Date('Y-m-d',strtotime("-6 day"));
$data[] = Date('Y-m-d',strtotime("-5 day"));
$data[] = Date('Y-m-d',strtotime("-4 day"));
$data[] = Date('Y-m-d',strtotime("-3 day"));
$data[] = Date('Y-m-d',strtotime("-2 day"));
$data[] = Date('Y-m-d',strtotime("-1 day")); //昨天
$data[] = Date('Y-m-d'); //今天
return $data;
}
//得到一个月的天数--如果是当前月份的话--天数为今天--截止到今天 (2016-12 2016-02)
public function getMonthDayCnt($month){
$now = Date('Y-m');
if($now == $month){ //当前月份的话
$cnt = Date('d'); //今天就是最大的一天
}else{
$time = strtotime($month);
$cnt = Date('t',$time); //某个月的天数
}
return intval($cnt) ?? 30; //如果都没有的话,默认30(你还可以判断一下未来的月份)
}
//得到某一年的天数--如果是当前年份的话--天数为今天--截止到今天 (2016)
public static function getYearDayCnt($year){
$now = Date('Y');
if($now == $year){ //当前年份的话
$cnt = Date('z'); //今天就是最大的一天
}else{
$time = strtotime($year.'-12-31'); //每年都有12月31日
$cnt = Date('z',$time); //0-365 从0开始
}
return intval($cnt + 1) ?? 365;
}
}
$dodo = new DodoDate(); //实例化该类
$arr = $dodo->getWeekDate(); //得到一周内的日期
echo '<pre>';
print_r($arr);
//最近一周的日期如下
/*Array(
[0] => 2016-12-02
[1] => 2016-12-03
[2] => 2016-12-04
[3] => 2016-12-05
[4] => 2016-12-06
[5] => 2016-12-07
[6] => 2016-12-08
)*/
$cnt1 = $dodo->getMonthDayCnt('2016-12'); //8 今天是12月8号
$cnt2 = $dodo->getMonthDayCnt('2016-11'); //30 11月份有30天
$cnt3 = $dodo->getMonthDayCnt('2016-2'); //29 今年的2月份
$cnt4 = $dodo->getMonthDayCnt('2015-02'); //28 去年的2月份
echo $cnt1.'<hr>';
echo $cnt2.'<hr>';
echo $cnt3.'<hr>';
echo $cnt4.'<hr>';
$year_cnt1 = $dodo->getYearDayCnt('2016'); //344 今天是12月8号 = 343+1
$year_cnt2 = $dodo->getMonthDayCnt('2015'); //365 2015年有365天 = 364+1
echo $year_cnt1.'<hr>';
echo $year_cnt2.'<hr>';
如果你给我的,和你给别人的是一样的,那我就不要了。——三毛
相关阅读
- 通过Google API客户端访问Google Play帐户报告PHP库
- PHP执行文件的压缩和解压缩方法
- 消息中间件MQ与RabbitMQ面试题
- 如何搭建一个拖垮公司的技术架构?
- Yii2中ElasticSearch的使用示例
热门文章
- 通过Google API客户端访问Google Play帐户报告PHP库
- PHP执行文件的压缩和解压缩方法
- 消息中间件MQ与RabbitMQ面试题
- 如何搭建一个拖垮公司的技术架构?
- Yii2中ElasticSearch的使用示例
最新文章
- 通过Google API客户端访问Google Play帐户报告PHP库
- PHP执行文件的压缩和解压缩方法
- 消息中间件MQ与RabbitMQ面试题
- 如何搭建一个拖垮公司的技术架构?
- Yii2中ElasticSearch的使用示例

