Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is a d3 time format?

Nouman Abbasi

d3-time-format is a JavaScript module used to parse or format dates in various locale-specific representations.

The module is inspired by the strptime and strftime functions from the C standard library.

The module provides a formatter and a parser:

  • formatter is used to format a JavaScript date object into a string representation

  • parser converts a string back to a date object

Installation

If you’re using NPM:

npm install d3-time-format

Otherwise, download the latest release. You can also load directly from d3js.org, either as a standalone library or as a part of D3.

Usage

To format a date, create a formatter from a specifiera string with the desired format directives indicated by %, then pass a date to the formatter (which returns a string). For instance, to convert the current date to a human-readable string:

let formatTime = d3.timeFormat("%B %d, %Y");
formatTime(new Date); // "January 15, 2020"

To create a parser to convert a string back to a date:

let parseTime = d3.timeParse("%B %d, %Y");
parseTime("January 15, 2020"); // Tue Jun 30 2015 00:00:00 GMT-0700 (PDT)

More elaborate conditional time formats can be implemented as well. For instance, a multi-scale time format that uses time intervals.

Code

As an example, let’s convert today’s date from a date object into a string and then convert it back into a date object:

Console

RELATED TAGS

javascript

CONTRIBUTOR

Nouman Abbasi
Copyright ©2022 Educative, Inc. All rights reserved
RELATED COURSES

View all Courses

Keep Exploring