JavaScript Date Formatting Strings with D3

Steve Ellwood
2 min readJun 23, 2022

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

  • %a - abbreviated weekday name.
  • %A - full weekday name.
  • %b - abbreviated month name.
  • %B - full month name.
  • %c - date and time, as "%a %b %e %H:%M:%S %Y".
  • %d - zero-padded day of the month as a decimal number [01,31].
  • %e - space-padded day of the month as a decimal number [ 1,31]; equivalent to %_d.
  • %H - hour (24-hour clock) as a decimal number [00,23].
  • %I - hour (12-hour clock) as a decimal number [01,12].
  • %j - day of the year as a decimal number [001,366].
  • %m - month as a decimal number [01,12].
  • %M - minute as a decimal number [00,59].
  • %L - milliseconds as a decimal number [000, 999].
  • %p - either AM or PM.
  • %S - second as a decimal number [00,61].
  • %U - week number of the year (Sunday as the first day of the week) as a decimal number [00,53].
  • %w - weekday as a decimal number [0(Sunday),6].
  • %W - week number of the year (Monday as the first day of the week) as a decimal number [00,53].
  • %x - date, as "%m/%d/%Y".
  • %X - time, as "%H:%M:%S".
  • %y - year without century as a decimal number [00,99].
  • %Y - year with century as a decimal number.
  • %Z - time zone offset, such as "-0700".
  • %% - a literal "%" character.

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

--

--

Steve Ellwood

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