# 一道面试题引发的思考

### 方法一

function monthDay(\$date) {
\$month31 = [1, 3, 5, 7, 8, 10, 12];
list(\$year, \$month) = explode('-',\$date);
if (\$month != 2) {
if (in_array(\$month, \$month31)) {
return "{\$year}-{\$month}-31";
} else {
return "{\$year}-{\$month}-30";
}
}
if (  \$year%4==0  && (\$year%100!=0 ||  \$year%400==0 ) ){
return "{\$year}-{\$month}-29";
}else{
return "{\$year}-{\$month}-28";
}
}

### 方法二

function endDayOfMonth(\$date) {
list(\$year, \$month) = explode('-',\$date);
\$nextYear = \$year;
\$nexMonth = \$month+1;
//如果是年底12月 下个月就是1月
if(\$month == 12) {
\$nexMonth = "01";
\$nextYear = \$year+1;
}
\$begin = "{\$year}-{\$month}-01 00:00:00";
\$end = "{\$nextYear}-{\$nexMonth}-01 00:00:00";
\$day = (strtotime(\$end) - strtotime(\$begin) )/ (24*60*60);
return "{\$year}-{\$month}-{\$day}";
}

### 方法三

function endDayOfMonth(\$date) {
list(\$year, \$month) = explode('-',\$date);
\$nextYear = \$year;
\$nexMonth = \$month+1;
//如果是年底12月 下个月就是1月
if(\$month == 12) {
\$nexMonth = "01";
\$nextYear = \$year+1;
}
\$end = "{\$nextYear}-{\$nexMonth}-01 00:00:00";
\$endTimeStamp = strtotime(\$end) - 1 ;
return date('Y-m-d',\$endTimeStamp);
}

### PHP自带函数实现

• php date 函数格式化
t 指定月份的天数; 如: "28" 至 "31"
\$date = '2018-08-08';
echo date('Y-m-t',strtotime(\$date));
• strtotime 字符串时间修饰词
last day of this month 时间字符 类似我们常说的 -1 day
echo date('Y-m-d',strtotime("last day of this month",strtotime('2018-02-01')));
echo date('Y-m-d',strtotime("last day of 2018-02"));
• php DateTime类 面向对象方式

\$date = new \DateTime('2000-02-01');
\$date->modify('last day of this month');
echo \$date->format('Y-m-d');

《L04 微信小程序从零到发布》

《L05 电商实战》

6个月前

666

6个月前

\$lastMonth = date('t', strtotime('-1 month', strtotime(date('Y-m', strtotime(\$startTime)) . '00:00:00')));
if (date("d", strtotime(\$startTime)) > \$lastMonth) {
\$last = \$lastMonth;
} else {
\$last = date('d', strtotime(\$startTime));
}
return date('Y-m-d', strtotime('-1 month', strtotime(date('Y-m', strtotime(\$startTime)) . '-' . \$last . ' 00:00:00')));
6个月前
6个月前

@xianyunyehe 好的。谢谢，我去学习学习。

6个月前

5个月前

@Ali 你这个太复杂

Carbon::parse('xxxx')->subMonthNoOverFlow()

5个月前

5个月前

Programer @ tes

7

49

486

41