需要一个判断函数,返回是否合法时间,PHP
ringa_lee
ringa_lee 2017-04-10 17:44:32
[PHP讨论组]
  1. 需要写一个函数isValidDate($date), 条件如下:

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;

}

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

ringa_lee
ringa_lee

ringa_lee

全部回复(3)
大家讲道理

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

ringa_lee

安装 Carbon

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;
}
怪我咯

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

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;

}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号