Search code examples
javascriptcsvd3.jsalasql

D3.js change time format and export data into csv


Have an original CSV(cities_9_2.csv) file like this:

date
"Wed, 01 Jul 2015 15:16:45 GMT"
"Wed, 01 Jul 2015 15:22:13 GMT"
"Wed, 01 Jul 2015 15:28:52 GMT"
"Wed, 01 Jul 2015 19:56:27 GMT"

Want to change the time format to 5/16/2016 12:00:00AM, have this d3 code below, the export file code is according to https://github.com/agershun/alasql/wiki/How-to-export-JavaScript-array-info-to-csv-on-client-side.

But currently the downloaded csv file is empty, does anyone know why?

var array_date = [];
var parser = d3.time.format("%Y/%m/%d  %I%P");

d3.csv("cities_9_2.csv", function(data){
  data.forEach(function(d) {
    var theDate = parser.parse(d.date);
    array_date.push(theDate);
  })
});


window.exportData = function exportData() {
    alasql("SELECT * INTO CSV('baba.csv') FROM ?",[array_date]);
}

Solution

  • For this date format in the CSV you don't need a parser, simply do the following.

    var array_date = [];
    
    d3.csv("my.csv", function(data){
      console.log(data)
      data.forEach(function(d) {
        var theDate = new Date(d.date);//the will get the correct date
        array_date.push(theDate);
      });
      console.log(array_date)
    });
    

    working code here

    If you want to convert it into a dateformat then do :

    var array_date = [];
    var parser = d3.time.format("%Y/%m/%d  %I%P");
    
    d3.csv("my.csv", function(data){
      console.log(data)
      data.forEach(function(d) {
        var theDate = parser(new Date(d.date));
        array_date.push(theDate);
      })
      console.log(array_date)
    });
    

    working code here