比较小于两个大于的时间变量



嗨,我是初学者,我想使用 javascript 将我的两个变量相互比较,如果 ts 大于 timecomp 显示警报"正常",否则如果小于 ts 则显示警报"错误"

像例子 TS 是 6:15,时间补偿是 6:00 将显示警报正常消息但如果小于将显示警报消息错误

<script> 
$(document).ready( function(){
var timecomp = "6:00"
var a = $('select[name="hours"] option:selected').val();
var a1 = $('select[name="mins"] option:selected').val();
var ts = a +":" a1;

 if( ts> timecomp)
{
alert("Okay");
}
else if ( ts<timecomp){

alert("Error");
}
});
</script>

如果您的字符串采用 "HH:MM:SS" 格式,并且您的时间是 24 小时制,则可以根据需要使用不等式来比较这两个字符串:

$(document).ready(function() {
  var timecomp = "06:00:00" // add :00 to the end for correct format 
  var a = "05"; // change these to see it working
  var a1 = "30"; // change these to see it working
  var ts = a + ":" + a1 + ":00"; // add ":00 for the seconds format"
  if (ts > timecomp) {
    alert("Okay");
  } else if (ts < timecomp) {
    alert("Error");
  } else {
    alert("Equal");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

var a = "10:20:45";
var b = "5:10:10";
var timeA = new Date();
timeA.setHours(a.split(":")[0],a.split(":")[1],a.split(":")[2]);
timeB = new Date();
timeB.setHours(b.split(":")[0],b.split(":")[1],b.split(":")[2]);

if(timeA>timeB) 
{
alert("A is large");
}
else{
alert("B is large");
}

在此处输入链接说明

setHours()定义时间,并在条件中使用new Date()

运行代码片段

var timecomp = new Date().setHours(6, 0, 0),
  a = 6, //$('select[name="hours"] option:selected').val();
  a1 = 15, // $('select[name="mins"] option:selected').val();
  ts = new Date().setHours(a, a1, 0);
if (new Date(ts).toLocaleTimeString() > new Date(timecomp).toLocaleTimeString()) {
  alert("Okay");
} else if (new Date(ts).toLocaleTimeString() < new Date(timecomp).toLocaleTimeString()) {
  alert("Error");
}

您可以比较日期对象。

var date1 = new Date(),
    date2 = new Date();
date1.setThours($('select[name="hours"] option:selected').val())
date1.setMinutes($('select[name="mins"] option:selected').val())
console.log(date1 > date2)

我建议使用 setHours() 函数而不是比较字符串。

所以你会有变量:

var startHour = new Date();
startHour.setHours(18, 00, 0); // 6:00 pm - 18:00
var endHour = new Date();
endHour.setHours(a, a1, 0); // 6.15 pm - 18:15

和警报:

if(endHour >= startHour){
    console.log("Okay");
}else{
    console.log("Error");
}

最新更新