英文:
Check whether the time lies between 2 times
问题
应用程序必须根据当前时间显示门是打开还是关闭的消息。
门在早上8:00到9:30之间或下午5:50之后、9:00之前打开,其他时间门都保持关闭。我想根据输入的时间显示消息。以下代码的输出是意外的,不正确的。
function isValid(date, h1, m1, h2, m2) {
var h = date.getHours();
var m = date.getMinutes();
return (h1 < h || h1 == h && m1 <= m) && (h < h2 || h == h2 && m <= m2);
}
function a() {
var current = new Date('2020-01-03 09:31:00');
if (isValid(current, 8, 0, 9, 30) || isValid(current, 5, 50, 21, 0)) {
return '门已打开';
} else {
return '请在早上8:00和9:30之间或下午5:50和9:00之间来';
}
}
a();
请注意,我只翻译了代码部分,没有包括额外的内容。
英文:
The application must display the message whether the gate is open or closed depending on the current time of the day.
The gate opens between 8:00am and before 9:30am OR after 5:50pm and before 9:00pm while the rest of the time the gate remains closed. I want to display the message based on the time input. The below code output is unexpected and incorrect.
function isValid(date, h1, m1, h2, m2) {
    var h = date.getHours();
    var m = date.getMinutes();
    return (h1 < h || h1 == h && m1 <= m) && (h < h2 || h == h2 && m <= m2);
}
function a() {
    var current = new Date('2020-01-03 09:31:00');
    if ((isValid(current, 8, 0, 9, 30)) || (isValid(current, 5, 50, 21, 0))) {
        return 'Gate is open'
    } else {
        return 'Please come after 8:00am and before 9:30am OR after 5:50pm and before 9:00pm';
    }
}a();
答案1
得分: 2
请使用 `17` 代替 `5` 作为下午时间
function isValid(date, h1, m1, h2, m2) {
var h = date.getHours();
var m = date.getMinutes();
return (h1 <= h && m1 <= m) && (h <= h2 && m <= m2);
}
function a() {
var current = new Date('2020-01-03 09:31:00');
if ((isValid(current, 8, 0, 9, 30)) || (isValid(current, 17, 50, 21, 0))){
return '大门开放';
} else {
return '请在早上 8:00 至 9:30 之间或下午 5:50 至 9:00 之间到来';
}
}
英文:
You've have to use 17
instead of 5
in the pm date
function isValid(date, h1, m1, h2, m2) {
var h = date.getHours();
var m = date.getMinutes();
return (h1 <= h && m1 <= m) && (h <= h2 && m <= m2);
}
function a() {
var current = new Date('2020-01-03 09:31:00');
if ((isValid(current, 8, 0, 9, 30)) || (isValid(current, 17, 50, 21, 0))){
return 'Gate is open'
} else {
return 'Please come after 8:00am and before 9:30am OR after 5:50pm and before 9:00pm';
}
}
答案2
得分: 0
你可以简单地将Date对象用作整数:
function isValid(date, h1, m1, h2, m2) {
var h = date.getHours();
var m = date.getMinutes();
var d1 = new Date(date);
d1.setHours(h1);
d1.setMinutes(m1);
var d2 = new Date(date);
d2.setHours(h2);
d2.setMinutes(m2);
return (date - d1) * (date - d2) < 0;
}
注意:这段代码没有被翻译,只是提供原始代码的中文注释。
英文:
You can use simply Date object as int:
function isValid(date, h1, m1, h2, m2) {
var h = date.getHours();
var m = date.getMinutes();
var d1 = new Date(date);
d1.setHours(h1);
d1.setMinutes(m1);
var d2 = new Date(date);
d2.setHours(h2);
d2.setMinutes(m2);
return (date-d1)*(date-d2) < 0;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论