我有两次格式“HH:MM”我想比较它们我有以下代码来获取我的格式的时间:
current_time = new Date(); hour = current_time.getHours(); minute = current_time.getMinutes(); if(hour<10){hour='0'+hour} if(minute<10){minute='0'+minute} my_time = hour+':'+minute;
这段代码是为了在减去GMT差异后得到时间:
d = new Date() var n = d.getTimezoneOffset(); var n1 = Math.abs(n); var difference = (n1/60); my_time = my_time - (0+difference);
现在应该将my_time的值与match_time的值进行比较:
match_time = 10:00;//for example if(my_time > match_time) { alert('yes'); } else { alert('No'); }
如何将这些值作为字符串的时间进行比较?
解决方法
使用Date对象.
Date.setHours()允许您指定小时,分钟,秒
var currentD = new Date(); var startHappyHourD = new Date(); startHappyHourD.setHours(17,30,0); // 5.30 pm var endHappyHourD = new Date(); endHappyHourD.setHours(18,0); // 6.30 pm console.log("happy hour?") if(currentD >= startHappyHourD && currentD < endHappyHourD ){ console.log("yes!"); }else{ console.log("no,sorry! between 5.30pm and 6.30pm"); }