问题
app.js
app.get('/user.html', function(req, res){
dbConnect.collection("users").find().toArray(function(err, docsData) {
res.render('user', {
data: docsData,
title: "EJS example",
header: "Some users"
});
});
});
user.html
<% data.forEach(function(user){ %>
<tr>
<td>
<%= user.date %>
</td>
</tr>
<% }) %>
output is 2014-12-24T09:47:07.436Z
this is the value coming from mongodb. I want to format this to Dec-24-2014. How to format it in embeddedjs.
回答1:
You can use toDateString()
to better format date in JavaScript :
<% data.forEach(function(user){ %>
<tr>
<td>
<%= user.date.toDateString() %>
</td>
</tr>
<% }) %>
If you want to display date in a custom format, you can use third party module like Moment.js. Using Moment.js your code would be like following:
app.js
var moment = require('moment');
app.get('/user.html', function(req, res){
dbConnect.collection("users").find().toArray(function(err, docsData) {
res.render('user', {
data: docsData,
title: "EJS example",
header: "Some users",
moment: moment
});
});
});
user.html
<% data.forEach(function(user){ %>
<tr>
<td>
<%= moment(user.date).format( 'MMM-DD-YYYY') %>
</td>
</tr>
<% }) %>
Hope this help!
来源:https://stackoverflow.com/questions/27635297/how-to-format-a-date-in-embeddedjs