【问题标题】:.timeFormat(%b %Y) not giving me the right dates.timeFormat(%b %Y) 没有给我正确的日期
【发布时间】:2020-09-16 16:10:49
【问题描述】:

我是 d3.js 的初学者。目前的目标是将日期列从 “2018-11-01” 变为 “Nov 18”。 日期从“2016-11-01”到“2020-08-01”,中间的每个日期只是每个月的第一天。

例如:

"2016-11-01", 
"2016-12-01",
"2017-01-01",
"2017-02-01",
"2017-03-01",
"2017-04-01",
"2017-05-01",

我使用的代码如下:

        var format = d3.timeFormat("%b %Y");    
        var data = d3.dsv(",", dsvPath, function (d) {
            return {
                //Year : getYear(new Date(+d.year,0,1)),
                
                date: format(new Date(d.date)),
                ['Catan=count']:+d['Catan=count'],
                ['Dominion=count']:+d['Dominion=count'],
                ['Codenames=count']:+d['Codenames=count'],
                ['Terraforming Mars=count']:+d['Terraforming Mars=count'],
                ['Gloomhaven=count']:+d['Gloomhaven=count'],
                ['Magic: The Gathering=count']:+d['Magic: The Gathering=count'],
                ['Dixit=count']:+d['Dixit=count'],
                ['Monopoly=count']:+d['Monopoly=count']
                //['Running Total'] : +d["running_total"]
            };
        }).then(function (data) {
            
            console.log(data[0]); 
            minDate = d3.min(data,function(d){console.log(d); return d.date;});
            maxDate = d3.max(data,function(d){console.log(d); return d.date;});
            console.log(minDate);

但是,对于最短日期,我得到的是 2017 年 4 月而不是 2016 年 11 月。最长日期是 2020 年 5 月而不是 2020 年 9 月。

当我在没有数据格式的情况下按原样读取数据时,minDate 和 maxDate 是正确的。但是,一旦我格式化,数据集中不存在的 Oct 2016 就会以某种方式被记录两次。

此外,控制台中的数据停留在“2020 年 7 月”:没有 2020 年 8 月和 2020 年 9 月。说实话我很困惑。

任何帮助将不胜感激! 谢谢!

【问题讨论】:

    标签: date d3.js formatting


    【解决方案1】:

    通过Date() 构造函数转换为日期是出了名的棘手。幸运的是,由于 D3 为我们提供了从日期到字符串的方法,it also has the reverse,从字符串到日期。

    我们的过程将是双重的:

    1. 对于特定格式的每个字符串,转换为Dated3.timeParse()
    2. 将每个日期转换为所需的字符串格式。
                (1.)                      (2.)
    "2016-01-01" ? Date<2016-01-01T00:0O> ? "January 2016"
             d3.timeParse                 d3.timeFormat
    

    您的代码中已经有 (2.),所以我们需要 (1.):

    var toDate = d3.timeParse("%Y-%M-%d");
    var format = d3.timeFormat("%b %Y"); // (2.)
    var data = d3.dsv(",", dsvPath, function (d) {
        return {
            date: format(toDate(d.date)),
        };
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多