[英]Using moment.js to determine if current time (in hour) is between certain hours
I am working on a function that'd greet its users with a time-aware greeting (Good Morning, Afternoon, Evening, Night).我正在开发一个 function,它会用时间感知问候(早安,下午,晚上,晚上)来迎接它的用户。 Here's the script that I've made这是我制作的脚本
import moment from "moment";
function generateGreetings(){
if (moment().isBetween(3, 12, 'HH')){
return "Good Morning";
} else if (moment().isBetween(12, 15, 'HH')){
return "Good Afternoon";
} else if (moment().isBetween(15, 20, 'HH')){
return "Good Evening";
} else if (moment().isBetween(20, 3, 'HH')){
return "Good Night";
} else {
return "Hello"
}
}
$("greet")
.css({
display: "block",
fontSize: "4vw",
textAlign: "center",
})
.text(generateGreetings() +", name")
But it simply wont work and just returns "Hello".但它根本不起作用,只会返回“Hello”。 I've also tried using我也尝试过使用
var currentTime = moment();
var currentHour = currentTime.hour();
and use currentHour
to replace moment()
inside the function but when I do so the site just dissapears.并使用currentHour
替换 function 中的moment()
但是当我这样做时,网站就会消失。 Hoping anyone here has any insight on what I should do to fix this issue.希望这里的任何人对我应该做些什么来解决这个问题有任何见解。
You are using moment().isBetween()
in a wrong way.您以错误的方式使用moment().isBetween()
。 You can see the correct method usage from here .您可以从这里查看正确的方法用法。 For your requirement, no need to use this isBetween
method.根据您的要求,无需使用此isBetween
方法。 You can simply get the hour and then check it against the if
condition.您可以简单地获取小时,然后根据if
条件检查它。
You can re-arrange your method like below.您可以重新安排您的方法,如下所示。
function generateGreetings(){
var currentHour = moment().format("HH");
if (currentHour >= 3 && currentHour < 12){
return "Good Morning";
} else if (currentHour >= 12 && currentHour < 15){
return "Good Afternoon";
} else if (currentHour >= 15 && currentHour < 20){
return "Good Evening";
} else if (currentHour >= 20 && currentHour < 3){
return "Good Night";
} else {
return "Hello"
}
}
The accepted answer can be simplified a lot;接受的答案可以简化很多; the elses
are completely superfluous because of the early returns:由于早期的回报, elses
人完全是多余的:
function greeting() {
const hour = moment().hour();
if (hour > 16){
return "Good evening";
}
if (hour > 11){
return "Good afternoon";
}
return 'Good morning';
}
@Thusitha @Thusitha
or you can use或者你可以使用
moment().hour()
instead of代替
moment().format('HH')(
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.