时间:2021-07-01 10:21:17 帮助过:15人阅读
需要写一个函数isValidDate($date), 条件如下:
- <code>function isValidDate($date)
- {
- //1. $date 是本周时 + time()要在$date前一天的18:00之前 = true
- //2. $date 为下周时 + time()要在本周四下午六点后 = true
- //3. 其余返回false. (注:一周从周一开始)
- $orderTime = strtotime($date);
- $now = time();
- if(date('W',$orderTime) == date('W',$now) && (strtotime($date,$now) - $now) > 86400/4) //预订前一天的18:00,截止预订
- {
- return true;
- }
- if(date('W',$orderTime) == date('W',$now) + 1 && $now > strtotime('saturday 18:05 -2 day',$now)) //预订第二周,周四下午六点及之后
- {
- return true;
- }
- return false;
- }</code>
其中,我写第二个条件的时候,发现条件覆盖的时间好像有点问题,想看下各位的见解哈。
需要写一个函数isValidDate($date), 条件如下:
- <code>function isValidDate($date)
- {
- //1. $date 是本周时 + time()要在$date前一天的18:00之前 = true
- //2. $date 为下周时 + time()要在本周四下午六点后 = true
- //3. 其余返回false. (注:一周从周一开始)
- $orderTime = strtotime($date);
- $now = time();
- if(date('W',$orderTime) == date('W',$now) && (strtotime($date,$now) - $now) > 86400/4) //预订前一天的18:00,截止预订
- {
- return true;
- }
- if(date('W',$orderTime) == date('W',$now) + 1 && $now > strtotime('saturday 18:05 -2 day',$now)) //预订第二周,周四下午六点及之后
- {
- return true;
- }
- return false;
- }</code>
其中,我写第二个条件的时候,发现条件覆盖的时间好像有点问题,想看下各位的见解哈。
怎么感觉这是要强行给别人做面试题的呢?既然条理都能列 123 了,实现应该不是问题吧。。。
安装 Carbon
- <code class="php">use Carbon\Carbon;
- /**
- * 校验日期
- * @param string $date 日期
- * @return boolean
- */
- function isValidDate($date)
- {
- // $date 是本周时 + time()要在$date前一天的18:00之前 = true
- if (Carbon::parse($date)->format('W') == Carbon::now()->format('W') &&
- time() < Carbon::parse($date)->subDay(1)->hour(18)->minute(0)->timestamp
- ) {
- return true;
- }
- // $date 为下周时 + time()要在本周四下午六点后 = true
- elseif (
- Carbon::parse($date)->format('W') == Carbon::now()->addWeek(1)->format('W') &&
- time() > Carbon::now()->startOfDay()->addDay(3)->hour(18)->minute(0)->timestamp
- ) {
- return true;
- }
- return false;
- }</code>
简单改一下题主的 if 语句 return
- <code>function isValidDate($date)
- {
- //1. $date 是本周时 + time()要在$date前一天的18:00之前 = true
- //2. $date 为下周时 + time()要在本周四下午六点后 = true
- //3. 其余返回false. (注:一周从周一开始)
- $orderTime = strtotime($date);
- $now = time();
- if(date('W',$orderTime) === date('W',$now)) // 当前周
- {
- // time()要在$date前一天的18:00之前 = true
- return $now < strtotime(date('Y-m-d 18:00:00',strtotime("$date -1 day")));
- }
- if(date('W',$orderTime) === (date('W',$now) + 1)) // 下周
- {
- // time()要在本周四下午六点后 = true
- return $now > strtotime(date('Y-m-d 18:00:00',strtotime( '+'. 4-date('w') .' days' )));
- }
- return false;
- }</code>