代码之家  ›  专栏  ›  技术社区  ›  user752746

节点.js和csv express日期格式

  •  0
  • user752746  · 技术社区  · 6 年前

    在使用csv express导出到csv时,是否有方法格式化日期“YYYY-MM-DD”?我在谷歌上搜索了很长一段时间,但什么也没找到。我用的是最新版本的节点.js、Express和MongoDB。

    这是默认的日期格式:“2018年8月9日星期四00:00:00 GMT-0700(太平洋夏令时)”。我只想要这个“2018-09-09”。

    我的问题是:

    router.get('/exportMonthlyPosts', (req, res) => {
       posts.find({...}, {id:1, title:1, post:1, postedOn:1}).sort(orderBy).lean()
        .then(post => {
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/csv');
            res.setHeader("Content-Disposition", 'attachment; filename=posts.csv');
            res.csv(report, true);
    
       });
    });
    

    样本数据:

    [
      { 
        _id: 5b64c23eef5b9c5c60fa42a0,
        title: 'Test Post',    
        post: 'Show me the money!',
        postedOn: 2018-08-29T00:00:00.000Z
      },
      { 
        _id: 5afb58408341f161a0c96608,
        title: 'Test Post 2',    
        post: 'Show me the money!',
        postedOn: 2018-08-29T00:00:00.000Z
      } 
    ]
    

    谢谢您!

    2 回复  |  直到 6 年前
        1
  •  3
  •   seunggabi    6 年前

    你试过这个吗? momentjs

    这是很酷的模块。

    https://momentjs.com/

    你能做到的。

    router.get('/exportMonthlyPosts', (req, res) => {
       posts.find({...}, {id:1, title:1, post:1, postedOn:1}).sort(orderBy).lean()
        .then(post => {
            // update postedOn.
            report.forEach((r) => {
                r.postedOn = moment(r.postedOn).format("YYYY-MM-DD")
            });
    
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/csv');
            res.setHeader("Content-Disposition", 'attachment; filename=posts.csv');
            res.csv(report, true);
    
       });
    });
    
        2
  •  0
  •   Lux    6 年前

    你可以改变你的生活 report 要将所有日期替换为字符串的新数据,请执行以下操作:

    const transformed = report.map(line => Object.entries(line).reduce((acc, [key, val]) => {
      acc[key] = val instanceof Date ? moment(val).format("YYYY-MM-DD") : val;
      return acc;
    }, {}));
    

    那就用吧 transformed 而不是 .

    推荐文章