How can i convert a time (12:30 am) into timestamp using javascript?

跟風遠走 提交于 2019-12-19 04:16:09

问题


Can anyone tell me how to that? I would like to compare 2 times and find out which one is greater? like 12:30 pm and 5:30 pm


回答1:


Use Date().parse()

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



回答2:


If the input is always similar as mentioned at the question:

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;
    }
}



回答3:


Just parse it in 12H time and compared them.
Running example in 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);



回答4:


Turn the times into javascript dates, call getTime() on the dates to return the number of milliseconds since midnight Jan 1, 1970.

Compare the getTime() returned values on each date to determine which is greater.

For 12 Hour format the code below will work.

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');
}



回答5:


Check out the below link-
http://www.dotnetspider.com/forum/162449-Time-Comparison-Javascript.aspx

You can test out your javascript online here -
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> 


来源:https://stackoverflow.com/questions/7539249/how-can-i-convert-a-time-1230-am-into-timestamp-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!