首頁  >  文章  >  後端開發  >  需要一個判斷函數,傳回是否合法時間,PHP

需要一個判斷函數,傳回是否合法時間,PHP

WBOY
WBOY原創
2016-12-01 00:56:301269瀏覽

  1. 需要寫一個函數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>

其中,我寫第二個條件的時候,發現條件覆蓋的時間好像有點問題,想看下各位的見解哈。

回覆內容:

  1. 需要寫一個函數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>
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn