2011-09-24 61 views

回答

1

使用日期()解析()

Date.parse('24/09/2011 15:21:41') 
+0

我的時間只有12小時的格式... – sam

+0

@sam Date.parse()'應該處理很多不同的格式。你真的嘗試過嗎? – Bojangles

1

。如果在問題中提到的輸入總是相似的:

var time1 = "12:30 pm"; 
var time2 = "5:30pm"; 
var time1_higher_than_time2 = compareTime(time1, time2); 
if(time1_higher_than_time2) alert("Time1 is higher than time 2"); 
else alert("Time1 is not higher than time 2. "); /* Time1 <= time2*/ 

/*Illustrative code. Returns true if time1 is greater than time2*/ 
function compareTime(time1, time2){ 
    var re = /^([012]?\d):([0-6]?\d)\s*(a|p)m$/i; 
    time1 = time1.match(re); 
    time2 = time2.match(re); 
    if(time1 && time2){ 
     var is_pm1 = /p/i.test(time1[3]) ? 12 : 0; 
     var hour1 = (time1[1]*1 + is_pm1) % 12; 
     var is_pm2 = /p/i.test(time2[3]) ? 12 : 0; 
     var hour2 = (time2[1]*1 + is_pm2) % 12; 
     if(hour1 != hour2) return hour1 > hour2; 

     var minute1 = time1[2]*1; 
     var minute2 = time2[2]*1; 
     return minute1 > minute2; 
    } 
} 
1

關閉時間轉換爲javascript dates,在日期上調用getTime()以返回自1970年1月1日午夜以來的毫秒數。

比較每個日期的返回值爲getTime() o確定哪個更大。

對於12小時格式,下面的代碼將工作。

var date1 = new Date('Sat Sep 24 2011 12:30:00 PM').getTime(); //12:30 pm 
var date2 = new Date('Sat Sep 24 2011 5:30:00 PM').getTime(); //5:30 pm 

if(date1 > date2) { 
    alert('date1 is greater'); 
} else if(date2 > date1) { 
    alert('date2 is greater'); 
} else { 
    alert('dates are equal'); 
} 
0

退房下面的鏈路
http://www.dotnetspider.com/forum/162449-Time-Comparison-Javascript.aspx

你可以在這裏在線測試出你的JavaScript -
http://www.w3schools.com/js/tryit.asp?filename=tryjs_events

<html> 
<head> 
<script type="text/javascript"> 
    var start = "01:00 PM"; 
    var end = "11:00 AM"; 
    var dtStart = new Date("1/1/2007 " + start); 
    var dtEnd = new Date("1/1/2007 " + end); 
    var difference_in_milliseconds = dtEnd - dtStart; 

    if (difference_in_milliseconds < 0) 
    { 
     alert("End date is before start date!"); 
    } 
</script> 
</head> 
<body> 

</body> 
</html> 
1

只是解析它在12H的時間和他們相比。
運行在here

var date1 = Date.parse('01/01/2001 12:30 PM'); 
var date2 = Date.parse('01/01/2001 5:30 PM'); 

console.log(date1 > date2); 
相關問題