首页 > 解决方案 > 从mongodb获取数据时如何使用momentjs格式化时间

问题描述

我不知道如何使用从 MongoDB 获取数据的时刻来格式化时间

我试过了<%= m(blog.created).format('MMMM Do YYYY, h:mm:ss a')%>

var moment = require('moment');
 var m = moment();

这是在我的 app.js 中设置架构

var blogSchema = new mongoose.Schema({
    title:  String,
    author: String,
    body:   String,
    image: String,
    created: {type:Date, default:Date.now}
});

在我的 Show.ejs 页面上

<div class="ui text main container segment">
 <div class="ui huge header"><%=blog.title%></div>
    <div class="ui top attached">
        <div class="item">
            <img class="ui centered rounded image" src="<%=blog.image%>">
            <div class="content">

                <span><%=blog.created%></span>

            </div>
            <div class="description">
                <p><%=blog.body%></p>
            </div>
        </div>

    </div>
</div>

我希望日期格式是这样的

moment().format('MMMM 做 YYYY, h:mm:ss a'); // 2019 年 2 月 6 日,凌晨 2:31:46

标签: node.jsmongodbmomentjsejsnode-modules

解决方案


试试这个:

var moment = require('moment');
app.locals.moment = require('moment'); // this makes moment available as a variable in every EJS page

在 Show.ejs 上

<%= moment(blog.created).format('MMMM Do YYYY, h:mm:ss a')%>

推荐阅读