-->

How to filter precisely on date?

2019-02-27 11:57发布

问题:

I'm using a lineChart to show created date (one field in my data), it works fine and I can select, but I need a more precise filter: only for items created today, this week, last week, this month, last month

Is there already an example of how it's done? I'm struggling on how to apply a daterange filter

回答1:

Since this question comes up now and then and it would be nice to have a decent example, I went back to NorthSide's question from a while back and fixed up the fiddle.

dc.js - add drop down to select date range

We'll define a second time dimension so that the charts are affected by it.

In this example we set the number of days as the option value, and then use that to calculate the date:

<select id="myDropDown">
  <option value="Infinity">All</option>
  <option value='30'>30 days</option>
  <option value='7'>7 days</option>
  <option value="2">Top 2 day</option>
  <option value="5">Top 5 day</option>
</select>

d3.select('#myDropDown').on('change', function(){ 
    var nd = new Date(now);
    nd.setDate(nd.getDate() - +this.value);
    filterDimension.filterRange([nd, now]);
    dc.redrawAll();    
});

http://jsfiddle.net/gordonwoodhull/400wd2nd/16/

There are more intelligent ways to calculate a month back and so on, but hopefully this is enough to get you started.



回答2:

I added a feature to be able to select the current day, current week or current month:

  d3.select('#date_select').on('change', function(){ 
    var nd = new Date(), now = new Date();
    switch (this.value) {
      case "today":
        nd = d3.time.day(now);
        break;
      case "week":
        nd = d3.time.monday(now);
        break;
      case "month":
        nd = d3.time.month(now);
        break;
      default:
        nd.setDate(nd.getDate() - +this.value);
    }
    dim.filterAll();
    dim.filterRange([nd, now]);
    //did not work graph.replaceFilter(dc.RangedFilter(nd, now));
    graph.redrawGroup();
  });

and the html being:

<select id="date_select">
  <option value="Infinity">All</option>
  <option value="today">Today</option>
  <option value='1'>last 24 hours</option>
  <option value="week">This week</option>
  <option value="month">This month</option>
  <option value='30'>last 30 days</option>
  <option value='90'>last 90 days</option>
</select>


标签: dc.js