node.js 如何格式化来自 MongoDB 的日期?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8675642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 14:56:41  来源:igfitidea点击:

How can I format a date coming from MongoDB?

node.jsmongooseexpress

提问by naivedeveloper

I'm using Jade to render my views from within Express.js. I am saving documents in MongoDB and using Mongoose to access my documents. I am saving a default date created when a new document is created and I am returning that date created attribute to the view, where is needs to be formatted. The format of the date being stored within MongoDB is:

我正在使用 Jade 从 Express.js 中呈现我的视图。我正在 MongoDB 中保存文档并使用 Mongoose 访问我的文档。我正在保存创建新文档时创建的默认日期,并将该日期创建属性返回到需要格式化的视图。MongoDB 中存储的日期格式为:

Thu Dec 29 2011 20:14:56 GMT-0600 (CST)

My question is: How do I format this date in Jade (or Mongoose or Node.JS) coming back from MongoDB?

我的问题是:如何在从 MongoDB 返回的 Jade(或 Mongoose 或 Node.JS)中格式化这个日期?

回答by s3v3n

I had exactly this requirements (expressjs, mongoose, jade) and this is how I solved it for myself.

我正好有这个要求(expressjs、mongoose、jade),这就是我自己解决的方法。

First of all I installed momentjswith npm install moment. Then I passed moment to view using this:

所有我首先安装momentjsnpm install moment。然后我通过时间来查看使用这个:

var moment = require('moment');

app.get('/', function(req, res){
    // find all jobs using mongoose model
    Job.find().exec(function(err, items){
        // pass moment as a variable
        res.render('status', { 'jobs': items, moment: moment });
    })
});

Then using it like this in Jade:

然后在 Jade 中像这样使用它:

table
  tr
    td Subject
    td Posted at
    td Status
  each job, i in jobs
    tr
      td #{job.subject}
      td #{moment(job.postedAt).format("YYYY-MM-DD HH:mm")}
      td #{job.status}

回答by Michelle Tilley

JavaScript has built-in support for dates. First, to get your string into a Date object:

JavaScript 内置了对日期的支持。首先,将您的字符串放入 Date 对象中:

date =  new Date('Thu Dec 29 2011 20:14:56 GMT-0600 (CST)')

Now you can use various methods on the date to get the data you need:

现在您可以在日期上使用各种方法来获取您需要的数据:

date.toDateString() // "Thu Dec 29 2011"
date.toUTCString()  // "Fri, 30 Dec 2011 02:14:56 GMT"
date.getMonth()     // 11
date.getDate()      // 29
date.getFullYear()  // 2011

You can see more methods on the MDN reference site. You can use these methods to build any kind of string you want.

您可以在 MDN 参考站点上查看更多方法。您可以使用这些方法来构建您想要的任何类型的字符串。

For more robust date/time parsing, formatting, and manipulation, you should definitely check out Moment.jsas mentioned by s3v3n in another answer.

为了更加稳健日期/时间分析,格式和操纵,你一定要看看Moment.js由s3v3n在另一个答复中提到。

回答by Wes Brown

I guess you haven't tried the easy way?

我猜你没有尝试过简单的方法?

#{storeddate.toDateString()}

回答by danmactough

Actually, you don't need another attribute in your Mongoose schema to store the creation date, as the _idhas that information. Instead, you can create a virtualon your Mongoose schema, like this:

实际上,您不需要 Mongoose 模式中的另一个属性来存储创建日期,因为它_id具有该信息。相反,您可以在 Mongoose 架构上创建一个虚拟的,如下所示:

YourSchema.virtual('date')
  .get(function() {
    return this._id.generationTime;
  });

That would return the raw Javascript date as the .dateattribute for each document.

这将返回原始 Javascript 日期作为.date每个文档的属性。

Then you can take that one step further and format the date you way you want to in that virtual:

然后,您可以更进一步,并在该虚拟环境中按照您想要的方式格式化日期:

YourSchema.virtual('date')
  .get(function() {
    return this._id.generationTime.toDateString();
  });

回答by AmJustSam

Here's an example on how can do that (Using EJS)

这是一个关于如何做到这一点的示例(使用 EJS)

   <%

    var monthNames = [
    "January", "February", "March",
    "April", "May", "June", "July",
    "August", "September", "October",
    "November", "December"
    ];

    var d = post.date.getDate();
    var m = monthNames[post.date.getMonth()];
    var y = post.date.getFullYear();

    %>

Now You Can Use These Variables Like This...

现在你可以像这样使用这些变量......

<small style="color: red"><%= post.date  %></small>

Source: https://medium.com/@littlelostify/how-to-format-mongoose-crappy-date-10df67d7a2d6

来源:https: //medium.com/@littlelostify/how-to-format-mongoose-crappy-date-10df67d7a2d6

回答by Y. Joy Ch. Singha

very easy method steps-

非常简单的方法步骤-

  1. install via npm moment --save

  2. declare var moment = require('moment');

  3. define the declare variable in res.render'filename.ejs',{moment: moment});

  4. put this ejs in your view file <%= moment(data.column_name_of_your_date).format( 'DD MMM YYYY'); %>

  1. 通过 npm moment --save 安装

  2. 声明 var moment = require('moment');

  3. 在 res.render'filename.ejs',{moment: moment}) 中定义声明变量;

  4. 将此 ejs 放入您的视图文件中 <%= moment(data.column_name_of_your_date).format( 'DD MMM YYYY'); %>

output is -- 09 Jun 2017

输出是 -- 2017 年 6 月 9 日

you can changed the format check it out in moment link for different format http://momentjs.com/

您可以更改格式,在不同格式的瞬间链接中查看它http://momentjs.com/

回答by Zhifeng Hu

My solution is:

我的解决办法是:

Add momentjsto your express application locals like this:
app.locals.moment = require('moment');

像这样将momentjs添加到您的 express 应用程序本地:
app.locals.moment = require('moment');

Then you can use moment in any jade files:
span='(Created at: ' + moment(obj.createTime).format("YYYY/MM/DD") + ')'

然后你可以在任何玉文件中使用 moment:
span='(Created at: ' + moment(obj.createTime).format("YYYY/MM/DD") + ')'

Reference: Making use of utility libraries in server-side Jade templates

参考: 在服务器端 Jade 模板中使用实用程序库