Dav*_*rto 8 javascript time momentjs
我正在开发一个功能,可以用时间感知的问候语(早上好,下午,晚上,晚上)向用户打招呼。这是我制作的脚本
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")
Run Code Online (Sandbox Code Playgroud)
但它根本不起作用,只返回“Hello”。我也尝试过使用
var currentTime = moment();
var currentHour = currentTime.hour();
Run Code Online (Sandbox Code Playgroud)
并用于在函数内部currentHour进行替换,但是当我这样做时,该网站就会消失。moment()希望这里的任何人都知道我应该做什么来解决这个问题。
Thu*_*tha 17
您使用moment().isBetween()方法错误。您可以从这里查看正确的方法用法。对于您的要求,无需使用此isBetween方法。您可以简单地获取小时,然后根据if条件进行检查。
您可以像下面这样重新安排您的方法。
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"
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7029 次 |
| 最近记录: |