【问题标题】:Changing ISODate into String Date ExpressJS将 ISODate 更改为字符串日期 ExpressJS
【发布时间】:2017-07-13 04:51:13
【问题描述】:

我如何在数组映射上更改我的值“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)
})}

但我的代码无法更改 :(

【问题讨论】:

    标签: node.js express isodate


    【解决方案1】:

    我已经在我的项目中写了一个方法来做到这一点,你可以使用这个代码来改变日期的格式。

    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;
    }
    

    此方法将返回两位数的月份或日期。前任。如果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
        };
    

    希望它对你有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-05
      • 2019-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-07
      • 2023-01-18
      • 2017-06-07
      相关资源
      最近更新 更多