我想实现这样的日期时间格式。1:00 am May 11 2020?
我正在使用mongoDB和EJS
如何在我的代码中做到这一点?
这是我的server.js代码。
// Import
const express = require('express')
const mongoose = require('mongoose');
const app = express();
mongoose.connect('mongodb://localhost/name_of_your_DB', {
useNewUrlParser: true
});
const UserSchema = new mongoose.Schema({
name: {
type: String
},
quote: {
type: String
},
created_at: {
type: Date,
default: Date.now
}
})
// Create an object that contains methods for mongoose to interface with MongoDB
const User = mongoose.model('User', UserSchema);
// Setting
app.use(express.static(__dirname + '/static'))
app.set('view engine', 'ejs')
app.set('views', __dirname + '/views')
app.use(express.json())
app.use(express.urlencoded({
extended: true
}))
// Routes
app.get('/', (req, res) => {
res.render('index')
});
app.post('/process', (req, res) => {
const user = new User();
user.name = req.body.name
user.quote = req.body.quote
user.save()
.catch(err => {
console.log('Error saving user:', err)
})
res.redirect('/quotes')
})
app.get('/quotes', (req, res) => {
User.find({}, (err, quotes) => {
var context = {
quotes: quotes
};
if (err) {
console.log('Something went wrong')
}
res.render("quotes", context);
});
});
app.get('/delete', (req, res) => {
User.remove({})
.then(data => {
res.json(data)
})
res.redirect('/quotes');
})
app.listen(8000)
这是我的EJS模板。
<div class="container bg-light" id="quote">
<h2>Here are the awesome quotes!</h2>
<div class="quote clearfix">
<% for (var user in quotes) { %>
<p class="quote"><b> "<%= quotes[user].quote %>"</b></p>
<p class="date"> - "<%= quotes[user].name %>" at <%= quotes[user].created_at %></p>
<hr>
<% } %>
<div class="row">
<a href="/" class="col">
<button class="btn btn-primary">Go back</button>
</a>
<a href="/delete" class="col">
<button class="btn btn-danger float-right" id="delete">Delete</button>
</a></div>
</div>
</div>
看一下 瞬间.js 为了能够使用 moment
ejs模板中的npm模块,修改上下文变量。
var context = {
quotes: quotes,
moment: moment
};
或者你也可以将Moment.js cdn脚本包含在ejs模板中。
然后在你的模板中,将相应的ejs块替换为。<%= moment(quotes[user].created_at).format('hh:mm a MMM DD YYYY') %>
也可以看看这个如何格式化一个JavaScript日期