节点csv-stringify格式时间戳列

Bch*_*ick 5 javascript csv node.js

我正在使用 Node csv-stringify 包将对象列表转换为 csv。

其中一列包含时间戳,并且 stringify 方法将其转换为纪元日期。

var stringify = require('csv-stringify');

...

input = [
{'field1':'val1', 'timemodified':'2016-08-16T23:00:00.000Z'},
...
]

stringify(input, function(err, output){
console.log(output);
})
Run Code Online (Sandbox Code Playgroud)

输出中修改的时间格式为:

1471388400000
Run Code Online (Sandbox Code Playgroud)

如何在输出中保持原始时间戳格式?

我尝试使用格式化程序选项,但没有效果: http://csv.adaltas.com/stringify/examples/

 stringify(input, {formatters: {
      "timemodified": function(value){
        return value.format("YYYY/MM/DD hh:mm:ss");
      }
    }},function(err, output) {
      fs.writeFile('userUpload.csv', output, 'utf8', function(err) {
        if (err) {
          console.log('Error - file either not saved or corrupted file saved.');
        } else {
          console.log('userUpload.csv file saved!');
        }
      });
    });
Run Code Online (Sandbox Code Playgroud)

Ida*_*gan 5

文档中,您可以将“cast”传递给选项。

例子:

const stringify = require('csv-stringify');
const assert = require('assert');

stringify([{
  name: 'foo',
  date: new Date(1970, 0)
},{
  name: 'bar',
  date: new Date(1971, 0)
}],{
  cast: {
    date: function (value) {
      return value.toISOString()
    }
  }
}, function (err, data) {
  assert.equal(
    data,
    "foo,1969-12-31T23:00:00.000Z\n" +
    "bar,1970-12-31T23:00:00.000Z\n"
  )
})
Run Code Online (Sandbox Code Playgroud)


Win*_*uen 0

我在没有自定义格式化程序的情况下尝试了您的代码,它按预期工作。我得到“val1,2016-08-16T23:00:00.000Z”作为输出。

但是如果我的输入中有一个日期对象,我会得到时间戳,例如:

input = [
{'field1':'val1', 'timemodified': new Date('2016-08-16T23:00:00.000Z')},
...
]
Run Code Online (Sandbox Code Playgroud)

请检查您的输入中是否有日期对象。