how to format a date in embeddedjs

喜欢而已 提交于 2019-12-12 12:14:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!