Custom multiscale time formats in d3

d3.time.scale has a neat time format that uses multiscale time formats . Is there an API or other way (for now) to specify multiscale time formats ?

I know that you can create a new d3.time.format , but it will not be multiscale.

Thanks.

+4
source share
2 answers

The multiscale time format does not display as an open API outside the standard returned by d3.time.scale s tickFormat .

However, the implementation itself is quite simple, so you can create your own multiscale time format without much work. A multiscale time format is simply an ordered array of time formats , each of which has a test function associated with it. The first test function, which returns true, determines which time format is used.

The time format used by d3.time.scale has the following formats (taken from time / scale.js ), indicated in reverse order:

  [".%L", function(d) { return d.getMilliseconds(); }], [":%S", function(d) { return d.getSeconds(); }], ["%I:%M", function(d) { return d.getMinutes(); }], ["%I %p", function(d) { return d.getHours(); }], ["%a %d", function(d) { return d.getDay() && d.getDate() != 1; }], ["%b %d", function(d) { return d.getDate() != 1; }], ["%B", function(d) { return d.getMonth(); }], ["%Y", d3_true] 

So, for example, if time has a nonzero millisecond field, then the format is ".% L"; otherwise, if it has a nonzero field, then ":% S" is used; etc.

+10
source

In version d3 version 4, d3.time.format has changed. Here is the new version of creating conditional time formatting:

https://github.com/d3/d3-time-format#d3-time-format

 var formatMillisecond = d3.timeFormat(".%L"), formatSecond = d3.timeFormat(":%S"), formatMinute = d3.timeFormat("%I:%M"), formatHour = d3.timeFormat("%I %p"), formatDay = d3.timeFormat("%a %d"), formatWeek = d3.timeFormat("%b %d"), formatMonth = d3.timeFormat("%B"), formatYear = d3.timeFormat("%Y"); function multiFormat(date) { return (d3.timeSecond(date) < date ? formatMillisecond : d3.timeMinute(date) < date ? formatSecond : d3.timeHour(date) < date ? formatMinute : d3.timeDay(date) < date ? formatHour : d3.timeMonth(date) < date ? (d3.timeWeek(date) < date ? formatDay : formatWeek) : d3.timeYear(date) < date ? formatMonth : formatYear)(date); } 
+2
source

Source: https://habr.com/ru/post/1238326/


All Articles