当前位置:Gxlcms > PHP教程 > 需要一个判断函数,返回是否合法时间,PHP

需要一个判断函数,返回是否合法时间,PHP

时间:2021-07-01 10:21:17 帮助过:15人阅读

  1. 需要写一个函数isValidDate($date), 条件如下:

  1. <code>function isValidDate($date)
  2. {
  3. //1. $date 是本周时 + time()要在$date前一天的18:00之前 = true
  4. //2. $date 为下周时 + time()要在本周四下午六点后 = true
  5. //3. 其余返回false. (注:一周从周一开始)
  6. $orderTime = strtotime($date);
  7. $now = time();
  8. if(date('W',$orderTime) == date('W',$now) && (strtotime($date,$now) - $now) > 86400/4) //预订前一天的18:00,截止预订
  9. {
  10. return true;
  11. }
  12. if(date('W',$orderTime) == date('W',$now) + 1 && $now > strtotime('saturday 18:05 -2 day',$now)) //预订第二周,周四下午六点及之后
  13. {
  14. return true;
  15. }
  16. return false;
  17. }</code>

其中,我写第二个条件的时候,发现条件覆盖的时间好像有点问题,想看下各位的见解哈。

回复内容:

  1. 需要写一个函数isValidDate($date), 条件如下:

  1. <code>function isValidDate($date)
  2. {
  3. //1. $date 是本周时 + time()要在$date前一天的18:00之前 = true
  4. //2. $date 为下周时 + time()要在本周四下午六点后 = true
  5. //3. 其余返回false. (注:一周从周一开始)
  6. $orderTime = strtotime($date);
  7. $now = time();
  8. if(date('W',$orderTime) == date('W',$now) && (strtotime($date,$now) - $now) > 86400/4) //预订前一天的18:00,截止预订
  9. {
  10. return true;
  11. }
  12. if(date('W',$orderTime) == date('W',$now) + 1 && $now > strtotime('saturday 18:05 -2 day',$now)) //预订第二周,周四下午六点及之后
  13. {
  14. return true;
  15. }
  16. return false;
  17. }</code>

其中,我写第二个条件的时候,发现条件覆盖的时间好像有点问题,想看下各位的见解哈。

怎么感觉这是要强行给别人做面试题的呢?既然条理都能列 123 了,实现应该不是问题吧。。。

安装 Carbon

  1. <code class="php">use Carbon\Carbon;
  2. /**
  3. * 校验日期
  4. * @param string $date 日期
  5. * @return boolean
  6. */
  7. function isValidDate($date)
  8. {
  9. // $date 是本周时 + time()要在$date前一天的18:00之前 = true
  10. if (Carbon::parse($date)->format('W') == Carbon::now()->format('W') &&
  11. time() < Carbon::parse($date)->subDay(1)->hour(18)->minute(0)->timestamp
  12. ) {
  13. return true;
  14. }
  15. // $date 为下周时 + time()要在本周四下午六点后 = true
  16. elseif (
  17. Carbon::parse($date)->format('W') == Carbon::now()->addWeek(1)->format('W') &&
  18. time() > Carbon::now()->startOfDay()->addDay(3)->hour(18)->minute(0)->timestamp
  19. ) {
  20. return true;
  21. }
  22. return false;
  23. }</code>

简单改一下题主的 if 语句 return

  1. <code>function isValidDate($date)
  2. {
  3. //1. $date 是本周时 + time()要在$date前一天的18:00之前 = true
  4. //2. $date 为下周时 + time()要在本周四下午六点后 = true
  5. //3. 其余返回false. (注:一周从周一开始)
  6. $orderTime = strtotime($date);
  7. $now = time();
  8. if(date('W',$orderTime) === date('W',$now)) // 当前周
  9. {
  10. // time()要在$date前一天的18:00之前 = true
  11. return $now < strtotime(date('Y-m-d 18:00:00',strtotime("$date -1 day")));
  12. }
  13. if(date('W',$orderTime) === (date('W',$now) + 1)) // 下周
  14. {
  15. // time()要在本周四下午六点后 = true
  16. return $now > strtotime(date('Y-m-d 18:00:00',strtotime( '+'. 4-date('w') .' days' )));
  17. }
  18. return false;
  19. }</code>

人气教程排行