我正在制作一个HTML表,应该根据时间使用JavaScript隐藏某些部分,例如;
6:30
6:45
7:05当前时间等于或大于6:30时,第一个单元格应隐藏。
我开始这样做的方式是;
var now = new Date(); //创建日期对象
var h = now.getHours(); //获取当前时间
var m = now.getMinutes(); //获取当前分钟
然后呢;
if(h> = 6& m> = 30){
$('table#truetable tr:first')。hide();
}
这不起作用(我认为问题出在最后一部分),因为它不会隐藏这个(第一个)单元格,比如7:25因为分钟数不大于30,这意味着这种方式在许多其他情况下不起作用。
我能解决这个问题吗?我需要以另一种方式做吗?
答案 0 :(得分:2)
按分钟比较:
if( h*60+m/*h:m*/ >= 6*60+30/*6:30*/ ){
}
答案 1 :(得分:1)
最简单的方法是分别在6点钟处理案例:
if (h > 6 || (h == 6 && m >= 30)) {
// Modify DOM
}
答案 2 :(得分:1)
我编写了一个函数,将hh:mm
或hh:mm:ss
格式的时间转换为秒。你可以在下面找到它:
function hourConvert(str) {
//this separates the string into an array with two parts,
//the first part is the hours, the second the minutes
//possibly the third part is the seconds
str = str.split(":");
//multiply the hours and minutes respectively with 3600 and 60
seconds = str[0] * 3600 + str[1] * 60;
//if the there were seconds present, also add them in
if (str.length == 3) seconds = seconds + str[2];
return seconds;
}
现在可以很容易地将时间相互比较:
if (hourConvert(str) > hourConvert("6:30")) //Do Stuff
查看实际操作:http://jsfiddle.net/TsEdv/1/
答案 3 :(得分:1)
var t = new Date()
undefined
t.getHours()
20
t.getHours()>=6
true
h = t.getMinutes()
51
t>=30
true
这确实有效。你的问题是你正在检查时间和分钟,这意味着如果分钟数小于30,它将返回false。
您的if转换为:
any hour bigger than six whose minutes are also bigger than 30
你的if条件应该是:
if(h>=6 && m>=30 || h>=7)
或仅限数字
if(h*60+m>= 390)