简体   繁体   English

用d3.js v.4解析日期

[英]Parsing dates with d3.js v.4

I'm trying to learn how to code with the d3.js by working on my first d3 mini project based on the Free Code Camp curriculum. 我正在尝试通过基于Free Code Camp课程的第一个d3 迷你项目来学习如何使用d3.js进行编码。 I am trying to make a simple bar graph with this json file . 我想用这个json文件制作一个简单的条形图。 I got stuck trying to format the dates in the file. 我试图格式化文件中的日期。 I've tried looking at the d3.js API and I am still lost. 我已经尝试过查看d3.js API ,但我仍然输了。 I would be very grateful for any advice that comes my way. 对于我的任何建议,我将非常感激。 Here is my code 这是我的代码

    // set the dimensions and margins of the graph
var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

//then make a function to parse the time
var parseDate = d3.timeFormat("%Y-%m-%d");

// set the ranges
var x = d3.scaleBand().rangeRound([0, width]).padding(0.1);
var y = d3.scaleLinear().range([height, 0],0.5);

// append the svg object to the body of the page
// append a 'group' element to 'svg'
// moves the 'group' element to the top left margin
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", 
          "translate(" + margin.left + "," + margin.top + ")");


//setup axis


// get the data
d3.json("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json").get(function(error,dataset){
  var d =dataset.data;
  d.forEach(function(datum, i) {
        d[0]=parseDate(datum[0]);
         //console.log(datum[1]);
    });
  //console.log(d[3][0]);

});

You want timeParse , not timeFormat : 你想要timeParse ,而不是timeFormat

var parseDate = d3.timeParse("%Y-%m-%d");

Using timeParse , 使用timeParse

the returned function parses a specified string, returning the corresponding date or null if the string could not be parsed according to this format's specifier. 返回的函数解析指定的字符串,返回相应的日期,如果根据此格式的说明符无法解析字符串,则返回null。

And this is how your forEach function should be: 这就是你的forEach函数应该是这样的:

data.forEach(function(d) {
    d[0] = parseDate(d[0]);
});

Here is a demo: 这是一个演示:

 var parseDate = d3.timeParse("%Y-%m-%d"); d3.json("https://raw.githubusercontent.com/FreeCodeCamp/ProjectReferenceData/master/GDP-data.json", function(json) { var data = json.data; data.forEach(function(d) { d[0] = parseDate(d[0]); }); console.log(data); }); 
 <script src="https://d3js.org/d3.v4.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM