如何在JavaScript中比较AM PM的时间

时间:2014-11-25 02:19:55

标签: javascript

我有两个字符串如下:

var a =“2014/4/24 3:10 PM” var b =“11/23/2014 7:45 AM”

如何将它们与JavaScript进行比较,以便我可以证明var b的时间发生在var之前?

3 个答案:

答案 0 :(得分:3)

<强> DEMO

将日期戳转换为UNIX时间码,然后比较两个

var a = "11/24/2014 3:10 PM";
var b = "11/23/2014 7:45 AM";

var aDate = new Date(a).getTime();
var bDate = new Date(b).getTime();

if(aDate < bDate){
    console.log('a happened before b');
}else if (aDate > bDate){
    console.log('a happend after b');
}else{
    console.log('a and b happened at the same time')
}

答案 1 :(得分:1)

您需要将日期解析为DateType,请查看以下代码段

&#13;
&#13;
var a = "11/24/2014 3:10 PM" 
b = "11/23/2014 7:45 AM"
var aDate= new Date(Date.parse(a));
var bDate = new Date(Date.parse(b));

if (aDate> bDate ){
  alert(aDate)   
}else{
  alert(bDate);       
}
&#13;
&#13;
&#13;

答案 2 :(得分:1)

试试这个: -

function modify_time(){
    var start_time = "10:30 PM";
    var end_time = "12:30 PM";
    start_time = start_time.split(" ");
    var time = start_time[0].split(":");
    var stime = time[0];
    if(start_time[1] == "PM" && stime<12) stime = parseInt(stime) + 12;
    start_time = stime + ":" + time[1] + ":00";

    end_time = end_time.split(" ");
    var time1 = end_time[0].split(":");
    var etime = time1[0];
    if(end_time[1] == "PM" && etime<12) etime = parseInt(etime) + 12;
    end_time = etime + ":" + time1[1] + ":00";

    if (start_time != '' && end_time != '') { 
        alert(start_time);
        alert(end_time);
        if (end_time <= start_time) {
            alert('select valid time');
        }
    }
}