两次错误比较

时间:2017-10-02 03:03:17

标签: javascript

这是我的代码

function get_time(){
    //Input first have Time
    var st = parseInt($(".el:first").attr("num"));

    //Input secound Have Time
    var end = parseInt($(".el:last").attr("num"));

    //Get Date 
    var d = new Date();

    // Get Hours And Minutes
    var h = ("0" + (d.getHours())).slice(-2); 
    var m = ("0" + (d.getMinutes())).slice(-2);

    //Convert Hours And Minutes To Number To Easy Comparison And Save It To Var t
    var t = h + '' + m;

    //Get ALL Times From First Input To Last Input 
    while(st <=end){
        //Time One
        var from = $('.from'+st).val().replace(':','');

        //Time Two
        var to = $('.to'+st).val().replace(':','');

        //if t > time1 And  < time2 
        if (t>= from && t<to){
            alert(true);
        } else {
            alert(false);
        }

        st++;
    }
}

每件事都有效但我有一个问题 例如:我有

t = 5:30 AM
From = 2:30
To = 6:30

真 但是

t = 5:30 AM
From = 3:30
To  = 2:30 (New Day)

错误

这是我的问题我不能设置Date Ex day或Mounth或Year Becouse我每天运行此代码

1 个答案:

答案 0 :(得分:0)

我建议将所有日期/时间转换为Date对象进行比较或转换为unix时间。比较字符串是1.不是很直接。 2.比数字慢。看起来混乱在于你的比较而不考虑上午和下午。如果您将所有数字转换为军事时间(23:30 === 11:30 pm),您可以保留比较,或者您可以加载来自&#34; st&#34;和&#34;结束&#34;变量到日期对象中以与当前日期进行比较。

&#13;
&#13;
function getTime(){
  var st = $(".el:first").attr("num"),
    end = $(".el:last").attr("num"),
    now = new Date();
    
    //custom function to parse elements into Dates
    var startDate = convertToDate(st);
    var endDate = convertToDate(end);
    
    if(startDate <= now && now < endDate){
      alert(true);
    }else{
      alert(false);
    }

}

function convertToDate(element){
    //do code here to create Date object and then return it
}
&#13;
&#13;
&#13;