【问题标题】:Node.js and csv-express date formatNode.js 和 csv-express 日期格式
【发布时间】:2018-09-07 23:22:17
【问题描述】:

在使用 csv-express 导出到 csv 时,有没有办法格式化日期“YYYY-MM-DD”?我已经用谷歌搜索了很长时间,但一无所获。我正在使用最新版本的 Node.js、Express 和 MongoDB。

这是默认日期格式:“Thu Aug 09 2018 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
  } 
]

谢谢!

【问题讨论】:

  • 只需在导出数据之前对其进行转换。
  • 嗨勒克斯,感谢您的回复。我目前正在学习 node.js 你能提供相同的代码吗?我将更新我的问题以包含我的查询。
  • 可能会显示您的代码如何导出它
  • 请查看更新后的问题,谢谢。

标签: javascript node.js express


【解决方案1】:

你试试这个? 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);

   });
});

【讨论】:

  • 嗨 seunggabi,我目前在这个项目中使用 moment.js。我尝试在我的选择中做这样的事情 (moment(new Date(postedOn).format("YYYY-MM-DD"):1) 但它没有用。我是 Node.js 的新手并且不太确定在哪里应用您的建议。如果您能提供示例代码,我们将不胜感激。
  • 好的,请在您的代码中提供有关post 的详细信息。我不知道post json。
  • 谢谢你,这对我来说很完美。谢谢你的例子!
【解决方案2】:

您可以将 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 而不是report

【讨论】:

    猜你喜欢
    • 2016-10-02
    • 2017-12-17
    • 2010-09-17
    • 1970-01-01
    • 1970-01-01
    • 2012-06-26
    • 1970-01-01
    • 2014-12-26
    • 1970-01-01
    相关资源
    最近更新 更多