我们已经给定了一个时间, 任务是在JavaScript的帮助下将时间四舍五入到最接近的四分之一小时。下面讨论了两种方法:
方法1:采用getMinutes()和getHours()在变量中获取分钟和小时的方法(例如分钟, 小时)), 将7.5加到分钟上, 除以15, 取整数值, 再乘以15, 得到最接近的四分之一分钟。如果该值超过60, 则将mod设为60。对于hrs, 如果mins为52, 并且hrs == 23, 则将hrs设置为0, 否则将其值增加1。
例子:
<!DOCTYPE HTML>
< html >
< head >
< title >
Round time to the nearest quarter
hour in JavaScript
</ title >
< style >
body {
text-align: center;
}
h1 {
color: green;
}
</ style >
</ head >
< body >
< h1 >
lsbin
</ h1 >
< p >
Click on button to round the time
to nearest quarter hour
</ p >
< p id = "gfg" ></ p >
< button onClick = "GFG_Fun()" >
click here
</ button >
< p id = "geeks" ></ p >
< script >
var up = document.getElementById('gfg');
var down = document.getElementById('geeks');
var date = new Date();
up.innerHTML = "" + date + "";
function GFG_Fun() {
// Getting minutes
var mins = date.getMinutes();
// Getting hours
var hrs = date.getHours();
var m = (parseInt((mins + 7.5) / 15) * 15) % 60;
// Converting '09:0' to '09:00'
m = m < 10 ? '0' + m : m;
var h = mins > 52 ? (hrs === 23 ? 0 : ++hrs) : hrs;
// Converting '9:00' to '09:00'
h = h < 10 ? '0' + h : h;
down.innerHTML = h + ":" + m;
}
</script>
</ body >
</ html >
输出如下:
方法二:采用getMinutes()和getHours()获取变量中分钟和小时的方法(例如分钟, 小时)。将分钟除以15, 将舍入值除以Math.round()并将其乘以15, 将得到最近的四分之一分钟。如果该值超过60, 则将mod设为60。对于hrs, 如果mins为52, 并且hrs == 23, 则将hrs设置为0, 否则将其值增加1。
例子:
<!DOCTYPE HTML>
< html >
< head >
< title >
Round time to the nearest quarter
hour in JavaScript
</ title >
< style >
body {
text-align: center;
}
h1 {
color: green;
}
</ style >
</ head >
< body >
< h1 >
lsbin
</ h1 >
< p >
Click on button to round the time
to nearest quarter hour
</ p >
< p id = "gfg" ></ p >
< button onClick = "GFG_Fun()" >
click here
</ button >
< p id = "geeks" ></ p >
< script >
var up = document.getElementById('gfg');
var down = document.getElementById('geeks');
var date = new Date();
up.innerHTML = "" + date + "";
function GFG_Fun() {
// Getting minutes
var mins = date.getMinutes();
// Getting hours
var hrs = date.getHours();
var m = (Math.round(mins/15) * 15) % 60;
// Converting '09:0' to '09:00'
m = m < 10 ? '0' + m : m;
var h = mins > 52 ? (hrs === 23 ? 0 : ++hrs) : hrs;
// Converting '9:00' to '09:00'
h = h < 10 ? '0' + h : h;
down.innerHTML = h + ":" + m;
}
</script>
</ body >
</ html >
输出如下: