Node csv-stringify format timestamp column

Viewed 2996

I'm converting a list of objects into a csv using Node csv-stringify package.

One of the columns contains a time-stamp and the stringify method is converting this to an epoch date.

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

...

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

stringify(input, function(err, output){
console.log(output);
})

The timemodified in output is formatted as:

1471388400000

How can I maintain the original time stamp formatting in the output?

I tried using the formatters option but it had no effect: 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!');
        }
      });
    });
3 Answers

From the docs, you can pass "cast" to the options.

Example:

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"
  )
})

You can find answer in doc examples

var moment = require('moment');
...
var stringifier = stringify(input, {
  formatters: {
    date: function(value) {
      return moment(value).format('YYYY-MM-DD');
    }
  }
}, function(err, output) {
  console.log(output);
});
Related