Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@zanarmstrong
Last active November 27, 2023 06:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zanarmstrong/ca0adb7e426c12c06a95 to your computer and use it in GitHub Desktop.
Save zanarmstrong/ca0adb7e426c12c06a95 to your computer and use it in GitHub Desktop.
d3 time formatting example
body {
margin: 20px 0px 0px 50px;
}
.formattext {
text-align: right;
}
.formatresult {
text-align: left;
padding-left: 40px;
}
.highlightedText {
font-weight: bold
}
// define variables
var formatlist = ["%Y-%m-%d", "%m/%d/%Y", "%H:%M","%H:%M %p", "%B %d", "%d %b", "%d-%b-%y", "%S s", "%M m", "%H h", "%a", "%A", "%d d", "%b", "%m/%Y",
"%b %Y", "%B", "%c", "%d", "%e", "%H", "%I", "%j",
"%m", "%M", "%L", "%p", "%S", "%U", "%w", "%W", "%x", "%X", "%y", "%Z"
];
var userTime = document.getElementById("userTime");
var colorLow = 'blue'
var colorHigh = 'red'
// add listener to call formatter function when user changes the number
userTime.addEventListener("change",
function(e) {
myFormats.changeNumber(userTime.value);
},
false
);
// need way to update list
formatSpecifier.addEventListener("change",
function(e) {
myFormats.addToList(formatSpecifier.value);
},
false
);
// create a little color scale function to make the output look pretty
function setColorScale(max) {
return d3.scale.linear()
.domain([0, max])
.interpolate(d3.interpolateRgb)
.range([colorLow, colorHigh])
}
// construct code/text pairs from list of formats I could use
var constructFormatObject = function(mylist) {
var types = [];
mylist.forEach(function(d) {
types.push({
code: d3.time.format(d),
text: 'd3.time.format("' + d + '")'
})
})
return types
}
//Jan. 28, 1986, 11:38:00 a.m. EST
//Mission Duration: 1 minute, 13 seconds
var myFormats = new ShowFormats(
formatlist,
new Date(1986, 0, 28, 11, 39, 13));
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Formatting Example</title>
<link rel="stylesheet" href="d3formatting.css">
</head>
<body>
<script src="https://d3js.org/d3.v3.min.js" charset="utf-8"></script>
This little tool helps you try out d3.time.format specifiers.<br>
Documentation for time format specifiers is <a href="https://github.com/mbostock/d3/wiki/Time-Formatting">here</a>.
<br><br>
Enter a date (year, month, day, hour, minutes, seconds):<br>
<input id="userTime" type="string"><br><br>
Add your own format specifier (ex: %a):<br>
<input id="formatSpecifier" type="string"><br><br>
Date formatted below: new Date(<span id="rawDate" class="highlightedText"></span>), or <span id="dateEntered" class="highlightedText"></span><br>
<table style="padding-top: 20px;"><thead>
<tr>
<th class="formattext">format specifier</th>
<th class="formatresult">resulting formatted number</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<script src="showFormatsConstructor.js"></script>
<script src="formatting.js"></script>
</body>
</html>
// set up showformats constructor
ShowFormats = function(formatList, number) {
// list of format specifiers to show
this.formatList = formatList;
this.formatObject = constructFormatObject(formatList);
this.dataset = Array.apply(0,
Array(this.formatObject.length)).map(function(x, y) {
return y;
});;
// number to format
this.number = number;
this.colorScale = setColorScale(this.dataset.length)
this.updateFormats()
}
ShowFormats.prototype.changeNumber = function(number) {
var format = d3.time.format("%Y,%m,%d,%H,%M,%S");
this.number = format.parse(number);
this.updateFormats();
}
ShowFormats.prototype.addToList = function(specifier) {
this.formatList.unshift(specifier)
this.formatObject = constructFormatObject(this.formatList);
// update dataset array w/ new length
this.dataset = Array.apply(0,
Array(this.formatObject.length)).map(function(x, y) {
return y;
});;
this.updateFormats();
}
ShowFormats.prototype.tdtextStyling = function(selection) {
selection.text(function(d) {
return self.formatObject[d].text;
})
.style("color", function(d) {
return self.colorScale(d)
})
.attr("class", "formattext");
}
ShowFormats.prototype.tdcodeStyling = function(selection) {
selection.text(function(d) {
return self.formatObject[d].code(self.number);
})
.style("color", function(d) {
return self.colorScale(d)
})
.attr("class", "formatresult");
}
ShowFormats.prototype.updateFormats = function() {
self = this;
document.getElementById('dateEntered').innerHTML = this.number;
document.getElementById('rawDate').innerHTML = this.number.getFullYear() +
',' + this.number.getMonth() +
',' + this.number.getDay() +
',' + this.number.getHours() +
',' + this.number.getMinutes() +
',' + this.number.getSeconds();
// bind with current dataset
this.selection = d3.selectAll("tbody").selectAll("tr")
.data(self.dataset);
// enter elements
var k = this.selection.enter().append("tr")
k.append("td")
.call(self.tdtextStyling);
k.append("td")
.call(self.tdcodeStyling);
// update elements
this.selection
.selectAll("td")
.text(function(d, i) {
if (i == 0) {
return self.formatObject[d].text;
}
if (i == 1) {
return self.formatObject[d].code(self.number);
}
})
.style("color", function(d) {
return self.colorScale(d)
})
.attr("class", function(d, i) {
if (i == 0) {
return "formattext"
} else {
return "formatresult"
}
})
}
@tonyfast
Copy link

Excellent tutorial. Thank you!

@curran
Copy link

curran commented May 12, 2023

@shum-dev
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment