根据天数,此代码的打印时间是否正确

时间:2017-08-31 05:22:01

标签: php date

请任何人检查并更正。

<?php
    $dt='2017-08-30';
    $dt1 = strtotime($dt);
    $dt2 = date("l", $dt1);
    $dt3 = strtolower($dt2);
    if(($dt3 == "Monday" ))
        {
            echo "6:00-8:00";
        } 
    else if(($dt3 == "tuesday" ))
        {
            echo "8:00-10:00";
        } 
    else    if(($dt3 == "wednesday" ))
        {
             echo "10:00-12:00";
        } 
    else    if(($dt3 == "thursday" ))
        {
             echo "12:00-14:00";
        } 
    else    if(($dt3 == "friday" ))
        {
            echo "14:00-16:00";
        } 
    else    if(($dt3 == "saturday" ))
        {
            echo "14:00-16:00";
        }
    else    if(($dt3 == "sunday" ))
        {
            echo "16:00-18:00";
        }
?>

如果

周一打印6-8

周二打印8-10

周三打印10-12

周四打印12-14

周五打印14-16

星期六打印16-18

周日打印16-18

1 个答案:

答案 0 :(得分:2)

请勿使用if语句,使用查找数组。它将更容易阅读和管理。

代码:(Demo

$lookup=['Monday'=>'6:00-8:00',
         'Tueday'=>'8:00-10:00',
         'Wednesday'=>'10:00-12:00',
         'Thursday'=>'12:00-14:00',
         'Friday'=>'14:00-16:00',
         'Saturday'=>'14:00-16:00',
         'Sunday'=>'16:00-18:00'];
if(function_exists('date_default_timezone_set')){
    date_default_timezone_set('Asia/Calcutta');  // whatever timezone you wish
}
$day=date("l");
    //$dt='2017-08-30';
    //$day=date("l",strtotime($dt));
echo $day,' ',$lookup[$day];

DateTime ...

$TZ=new DateTimeZone('Asia/Kolkata');  // whatever timezone you wish
$now=new DateTime('NOW',$TZ);
$day=$now->format('l');
echo $day,' ',$lookup[$day];

输出:

Wednesday 10:00-12:00