我正在尝试创建一个网站,其中包含欢迎消息,但会根据一天中的时间而变化。例如:早上好(2am-11:59 AM),下午好(12:00 pm-4:59 pm)晚上好(5:00 pm-1:59 am)。如何在带有把手的Node.JS中执行此操作。
const express = require('express');
const path = require('path');
const hbs = require('express-handlebars');
// const request = require('request');
// Init App
const app = express();
// Json File
const json = require("./data.json");
// Moment.js
var moment = require('moment');
// Load View Engine
app.engine('hbs', hbs({extname: 'hbs', defaultLayout: 'layout',
layoutsDir: __dirname + '/views/layouts/'}));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
app.use(express.static(__dirname+'/public'));
// Home Route
app.get('/', function(req, res){
res.render('index', {
title: 'Node Park',
hotel: 'Nodemon',
firstName: json.payload.data.Source_FirstName,
lastname: json.payload.data.Source_LastName,
date: moment().format('ll'),
time: moment().format('LT'),
});
});
// Start Server
app.listen(5000, function(){
console.log('Port 5000 open for business.');
});
查看:
<div id="body-container">
<div id="header">
<div id="logo-content">
<div id="logo"></div>
</div>
<div id="welcome">
<p>Welcome {{ firstName }} {{ lastname }} to NODE Park.</p>
</div>
<div id="time-side">
<div id="time-content">
<p> {{ date }} <br> {{ time }} </p>
</div>
</div>
</div>
{{!-- end of header --}}
<div id="background">
<img src="images/villaView.jpg" alt="villaView">
</div>
<div id="footer">
<p> <br> © 2018 FreshOceans </p>
</div>
答案 0 :(得分:1)
您需要编写函数,该函数根据时间返回正确的消息。很简单。
function generateModt()
{
var ret = " ";
var morning = moment('08:00am', 'hh:mma');
var noon = moment('11:59am', 'hh:mma');
var currentTime = moment();
if(currentTime.isBefore(noon) && currentTime.isAfter(morning))
{
ret = "Hello, it's morning";
}
else... //You need to write rest of your cases
return ret;
}
// Home Route
app.get('/', function(req, res){
res.render('index', {
title: 'Node Park',
hotel: 'Nodemon',
firstName: json.payload.data.Source_FirstName,
lastname: json.payload.data.Source_LastName,
date: moment().format('ll'),
time: moment().format('LT'),
modt: generateModt()
});
});
然后只需将{{modt}}添加到您的网页即可。
无论如何,也许您需要以不同的方式获取currentTime,仅获取时间而非日期。
您在这里有类似的问题: How to use Moment.JS to check whether the current time is between 2 times
编辑: 您可以检查这是否只能获取时间,而不能获取日期:
moment().toDate().getTime()