JavaScript Date Formatting Strings with D3

In the Microsoft world it’s been possible to create custom formats for date/times for many years so when I came to wanting to do the same thing in JavaScript I found it surprisingly tricky to find the information I wanted.

The problem is that I have a set of data I want to present on a web page. In this case I might want the dates to be represented as just the month and year e.g. May 2022. JavaScript has a lot of built in functions that can help with this but I wanted to use the formatters that I was familiar with, for example in .NET the date above could be created with something like

date.ToString("MMM YYYY");

I believed this could be done in JavaScript but it was remarkably elusive. Fortunately this data was being visualised using the fantastic D3 library. This has some documentation for time formatting which I have taken the liberty of reproducing here

so for my example above I can use %b and %Y to get what I want.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Steve Ellwood

Senior Integrations Officer at Doncaster Council Any views expressed are entirely my own.