node.js - 将 ISODate 更改为字符串日期 ExpressJS

标签 node.js express isodate

如何更改数组映射上的“created_at”属性值。

这是我的对象

{ _id: 59661cba54481612500d3043,
  author_id: 595e51e0f14cff12e896ead7,
  updated_at: 2017-07-12T13:07:52.913Z,
  created_at: 2017-12-06T17:00:00.000Z,
  trash: false,
  tag: [ 595e51e0f14cff12e896ead9, 595e51e0f14cff12e896ead3 ],
  category: [ 595e51e0f14cff12e896ead9, 595e51e0f14cff12e896ead3 ],
  title: 'test2' }

我想将created_at的值更改为简单的日期,如下所示=“13-07-2017”

这是我的代码

function article(req, res) {
postArticle.find({}, function(err, articles) {
    articles.map(function(article) {
        var dateCreate = new Date(article.created_at);
        var newDate = dateCreate.getDate()+'-' +(dateCreate.getMonth()+1)+'-' +dateCreate.getFullYear();
        article.created_at = newDate;
        console.log(dateCreate);
        console.log(newDate)
        console.log(article)
    });

    // res.render('admin/article/index', {title: 'Article Posts', posts: article})
    // res.json({title: 'article', posts: article})
    // console.log(article)
})}

但是我的代码无法更改:(

最佳答案

我在我的项目中编写了一个方法来执行此操作,您可以使用此代码来更改日期的格式。

function article(req, res) {
postArticle.find({}, function(err, articles) {
    articles.map(function(article) {
        var dateCreate = formatDate(article.created_at);
        var newDate = formatDate(new Date());
        article.created_at = newDate;
        console.log(dateCreate);
        console.log(newDate)
        console.log(article)
    });

    // res.render('admin/article/index', {title: 'Article Posts', posts: article})
    // res.json({title: 'article', posts: article})
    // console.log(article)
})}

格式化日期的方法:

var formatDate = function (date) {
    var myDate = new Date(date);

    var y = myDate.getFullYear(),
        m = myDate.getMonth() + 1, // january is month 0 in javascript
        d = myDate.getDate();

    // Get the DD-MM-YYYY format
    return formatDigit(d) + "-" + formatDigit(m) + "-" + y;
}

此方法将返回两位数的月份或日期。前任。 if formatDigit(4)//04

    /**
     * Format a month or day in two digit.
     */
    var formatDigit = function (val) {
        var str = val.toString();
        return (str.length < 2) ? "0" + str : str
    };

希望它对您有用。

关于node.js - 将 ISODate 更改为字符串日期 ExpressJS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45071649/

相关文章:

node.js - 如何在 Dockerfile 中设置 ENV 变量(来自 .txt 文件的内容)?

javascript - 'serving static files' 到底是什么意思?

scala - joda 时间 ISO 日期时间格式

MongoDB 按日期以字符串格式聚合不起作用

MongoDB - 查询可用日期范围以及酒店的日期范围

javascript - 简单的$ avg查询Node.js

javascript - 从 ES6 javascript 中的字符串动态创建方法(非浏览器)

javascript - 在 Node - Express 中执行 POST 操作后更改 EJS 中的元素样式

css - 如何使用 node、express 和 ejs 包含 css 文件?

mysql - 如何在nodejs的单个文件中提供mysql数据库连接