Built with blockbuilder.org
Created
August 30, 2017 19:24
-
-
Save Fasani/1600a06776918c22cdc4cfb31d210c84 to your computer and use it in GitHub Desktop.
Simple Custom Time Formats with D3 V4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
license: mit |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<svg width="960" height="500"></svg> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script> | |
var svg = d3.select("svg"), | |
margin = {top: 250, right: 40, bottom: 250, left: 40}, | |
width = svg.attr("width") - margin.left - margin.right, | |
height = svg.attr("height") - margin.top - margin.bottom; | |
var formatMillisecond = d3.timeFormat(".%L"), | |
formatSecond = d3.timeFormat(":%S"), | |
formatMinute = d3.timeFormat("%I:%M"), | |
formatHour = d3.timeFormat("%H:%M"), | |
formatDay = d3.timeFormat("%a %d"), | |
formatWeek = d3.timeFormat("%b %d"), | |
formatMonth = d3.timeFormat("%B"), | |
formatYear = d3.timeFormat("%Y"); | |
var x = d3.scaleTime() | |
.domain([new Date(2000, 0, 1), new Date(2000, 0, 2)]) | |
.range([0, width]); | |
svg.append("g") | |
.attr("transform", "translate(" + margin.left + "," + margin.top + ")") | |
.call(d3.axisBottom(x) | |
.tickFormat(multiFormat)); | |
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); | |
} | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment