Skip to content

Commit

Permalink
Format dates as ISO 8601. Fixes #41.
Browse files Browse the repository at this point in the history
  • Loading branch information
mbostock committed Feb 7, 2019
1 parent c6b02ea commit 30be739
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 4 deletions.
9 changes: 5 additions & 4 deletions src/dsv.js
Original file line number Diff line number Diff line change
Expand Up @@ -112,10 +112,11 @@ export default function(delimiter) {
return row.map(formatValue).join(delimiter);
}

function formatValue(text) {
return text == null ? ""
: reFormat.test(text += "") ? "\"" + text.replace(/"/g, "\"\"") + "\""
: text;
function formatValue(value) {
return value == null ? ""
: value instanceof Date ? value.toJSON()
: reFormat.test(value += "") ? "\"" + value.replace(/"/g, "\"\"") + "\""
: value;
}

return {
Expand Down
5 changes: 5 additions & 0 deletions test/csv-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,11 @@ tape("csvFormat(array) takes an array of objects as input", function(test) {
test.end();
});

tape("csvFormat(array) converts dates to ISO 8601", function(test) {
test.deepEqual(dsv.csvFormat([{date: new Date(Date.UTC(2018, 0, 1))}]), "date\n2018-01-01T00:00:00.000Z");
test.end();
});

tape("csvFormat(array) escapes field names and values containing delimiters", function(test) {
test.deepEqual(dsv.csvFormat([{"foo,bar": true}]), "\"foo,bar\"\ntrue");
test.deepEqual(dsv.csvFormat([{field: "foo,bar"}]), "field\n\"foo,bar\"");
Expand Down

0 comments on commit 30be739

Please sign in to comment.