• Stars
    star
    324
  • Rank 124,739 (Top 3 %)
  • Language
    JavaScript
  • License
    ISC License
  • Created almost 9 years ago
  • Updated 7 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Parse and format times, inspired by strptime and strftime.

d3-time-format

This module provides an approximate JavaScript implementation of the venerable strptime and strftime functions from the C standard library, and can be used to parse or format dates in a variety of locale-specific representations. To format a date, create a formatter from a specifier (a string with the desired format directives, indicated by %); then pass a date to the formatter, which returns a string. For example, to convert the current date to a human-readable string:

const formatTime = d3.timeFormat("%B %d, %Y");
formatTime(new Date); // "June 30, 2015"

Likewise, to convert a string back to a date, create a parser:

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

You can implement more elaborate conditional time formats, too. For example, here鈥檚 a multi-scale time format using time intervals:

const formatMillisecond = d3.timeFormat(".%L"),
    formatSecond = d3.timeFormat(":%S"),
    formatMinute = d3.timeFormat("%I:%M"),
    formatHour = d3.timeFormat("%I %p"),
    formatDay = d3.timeFormat("%a %d"),
    formatWeek = d3.timeFormat("%b %d"),
    formatMonth = d3.timeFormat("%B"),
    formatYear = d3.timeFormat("%Y");

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);
}

This module is used by D3 time scales to generate human-readable ticks.

Installing

If you use npm, npm install d3-time-format. You can also download the latest release on GitHub. For vanilla HTML in modern browsers, import d3-time-format from Skypack:

<script type="module">

import {timeFormat} from "https://cdn.skypack.dev/d3-time-format@4";

const format = timeFormat("%x");

</script>

For legacy environments, you can load d3-time-format鈥檚 UMD bundle from an npm-based CDN such as jsDelivr; a d3 global is exported:

<script src="https://cdn.jsdelivr.net/npm/d3-array@3"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-time@3"></script>
<script src="https://cdn.jsdelivr.net/npm/d3-time-format@4"></script>
<script>

const format = d3.timeFormat("%x");

</script>

Locale files are published to npm and can be loaded using d3.json. For example, to set Russian as the default locale:

d3.json("https://cdn.jsdelivr.net/npm/d3-time-format@3/locale/ru-RU.json").then(locale => {
  d3.timeFormatDefaultLocale(locale);

  const format = d3.timeFormat("%c");

  console.log(format(new Date)); // 锌芯薪械写械谢褜薪懈泻,  5 写械泻邪斜褉褟 2016 谐. 10:31:59
});

API Reference

# d3.timeFormat(specifier) 路 Source

An alias for locale.format on the default locale.

# d3.timeParse(specifier) 路 Source

An alias for locale.parse on the default locale.

# d3.utcFormat(specifier) 路 Source

An alias for locale.utcFormat on the default locale.

# d3.utcParse(specifier) 路 Source

An alias for locale.utcParse on the default locale.

# d3.isoFormatSource

The full ISO 8601 UTC time formatter. Where available, this method will use Date.toISOString to format.

# d3.isoParseSource

The full ISO 8601 UTC time parser. Where available, this method will use the Date constructor to parse strings. If you depend on strict validation of the input format according to ISO 8601, you should construct a UTC parser function:

const strictIsoParse = d3.utcParse("%Y-%m-%dT%H:%M:%S.%LZ");

# locale.format(specifier) 路 Source

Returns a new formatter for the given string specifier. The specifier string may contain the following directives:

  • %a - abbreviated weekday name.*
  • %A - full weekday name.*
  • %b - abbreviated month name.*
  • %B - full month name.*
  • %c - the locale鈥檚 date and time, such as %x, %X.*
  • %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.
  • %f - microseconds as a decimal number [000000, 999999].
  • %g - ISO 8601 week-based year without century as a decimal number [00,99].
  • %G - ISO 8601 week-based year with century as a decimal number.
  • %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.*
  • %q - quarter of the year as a decimal number [1,4].
  • %Q - milliseconds since UNIX epoch.
  • %s - seconds since UNIX epoch.
  • %S - second as a decimal number [00,61].
  • %u - Monday-based (ISO 8601) weekday as a decimal number [1,7].
  • %U - Sunday-based week of the year as a decimal number [00,53].
  • %V - ISO 8601 week of the year as a decimal number [01, 53].
  • %w - Sunday-based weekday as a decimal number [0,6].
  • %W - Monday-based week of the year as a decimal number [00,53].
  • %x - the locale鈥檚 date, such as %-m/%-d/%Y.*
  • %X - the locale鈥檚 time, such as %-I:%M:%S %p.*
  • %y - year without century as a decimal number [00,99].
  • %Y - year with century as a decimal number, such as 1999.
  • %Z - time zone offset, such as -0700, -07:00, -07, or Z.
  • %% - a literal percent sign (%).

Directives marked with an asterisk (*) may be affected by the locale definition.

For %U, all days in a new year preceding the first Sunday are considered to be in week 0. For %W, all days in a new year preceding the first Monday are considered to be in week 0. Week numbers are computed using interval.count. For example, 2015-52 and 2016-00 represent Monday, December 28, 2015, while 2015-53 and 2016-01 represent Monday, January 4, 2016. This differs from the ISO week date specification (%V), which uses a more complicated definition!

For %V,%g and %G, per the strftime man page:

In this system, weeks start on a Monday, and are numbered from 01, for the first week, up to 52 or 53, for the last week. Week 1 is the first week where four or more days fall within the new year (or, synonymously, week 01 is: the first week of the year that contains a Thursday; or, the week that has 4 January in it). If the ISO week number belongs to the previous or next year, that year is used instead.

The % sign indicating a directive may be immediately followed by a padding modifier:

  • 0 - zero-padding
  • _ - space-padding
  • - - disable padding

If no padding modifier is specified, the default is 0 for all directives except %e, which defaults to _. (In some implementations of strftime and strptime, a directive may include an optional field width or precision; this feature is not yet implemented.)

The returned function formats a specified date, returning the corresponding string.

const formatMonth = d3.timeFormat("%B"),
    formatDay = d3.timeFormat("%A"),
    date = new Date(2014, 4, 1); // Thu May 01 2014 00:00:00 GMT-0700 (PDT)

formatMonth(date); // "May"
formatDay(date); // "Thursday"

# locale.parse(specifier) 路 Source

Returns a new parser for the given string specifier. The specifier string may contain the same directives as locale.format. The %d and %e directives are considered equivalent for parsing.

The returned function parses a specified string, returning the corresponding date or null if the string could not be parsed according to this format鈥檚 specifier. Parsing is strict: if the specified string does not exactly match the associated specifier, this method returns null. For example, if the associated specifier is %Y-%m-%dT%H:%M:%SZ, then the string "2011-07-01T19:15:28Z" will be parsed as expected, but "2011-07-01T19:15:28", "2011-07-01 19:15:28" and "2011-07-01" will return null. (Note that the literal Z here is different from the time zone offset directive %Z.) If a more flexible parser is desired, try multiple formats sequentially until one returns non-null.

# locale.utcFormat(specifier) 路 Source

Equivalent to locale.format, except all directives are interpreted as Coordinated Universal Time (UTC) rather than local time.

# locale.utcParse(specifier) 路 Source

Equivalent to locale.parse, except all directives are interpreted as Coordinated Universal Time (UTC) rather than local time.

Locales

# d3.timeFormatLocale(definition) 路 Source

Returns a locale object for the specified definition with locale.format, locale.parse, locale.utcFormat, locale.utcParse methods. The definition must include the following properties:

  • dateTime - the date and time (%c) format specifier (e.g., "%a %b %e %X %Y").
  • date - the date (%x) format specifier (e.g., "%m/%d/%Y").
  • time - the time (%X) format specifier (e.g., "%H:%M:%S").
  • periods - the A.M. and P.M. equivalents (e.g., ["AM", "PM"]).
  • days - the full names of the weekdays, starting with Sunday.
  • shortDays - the abbreviated names of the weekdays, starting with Sunday.
  • months - the full names of the months (starting with January).
  • shortMonths - the abbreviated names of the months (starting with January).

For an example, see Localized Time Axis II.

# d3.timeFormatDefaultLocale(definition) 路 Source

Equivalent to d3.timeFormatLocale, except it also redefines d3.timeFormat, d3.timeParse, d3.utcFormat and d3.utcParse to the new locale鈥檚 locale.format, locale.parse, locale.utcFormat and locale.utcParse. If you do not set a default locale, it defaults to U.S. English.

For an example, see Localized Time Axis.

More Repositories

1

d3

Bring data to life with SVG, Canvas and HTML. 馃搳馃搱馃帀
JavaScript
106,311
star
2

d3-shape

Graphical primitives for visualization, such as lines and areas.
JavaScript
2,458
star
3

d3-plugins

[DEPRECATED] A repository for sharing D3.js V3 plugins.
JavaScript
1,808
star
4

d3-force

Force-directed graph layout using velocity Verlet integration.
JavaScript
1,702
star
5

d3-scale

Encodings that map abstract data to visual representation.
JavaScript
1,567
star
6

d3-queue

Evaluate asynchronous tasks with configurable concurrency.
JavaScript
1,411
star
7

d3-hierarchy

2D layout algorithms for visualizing hierarchical data.
JavaScript
1,064
star
8

d3-geo-projection

Extended geographic projections for d3-geo.
JavaScript
1,058
star
9

d3-geo

Geographic projections, spherical shapes and spherical trigonometry.
JavaScript
988
star
10

d3-scale-chromatic

Sequential, diverging and categorical color scales.
JavaScript
787
star
11

d3-sankey

Visualize flow between nodes in a directed acyclic network.
JavaScript
763
star
12

d3-format

Format numbers for human consumption.
JavaScript
611
star
13

d3-ease

Easing functions for smooth animation.
JavaScript
604
star
14

d3-delaunay

Compute the Voronoi diagram of a set of two-dimensional points.
JavaScript
588
star
15

d3-selection

Transform the DOM by selecting elements and joining to data.
JavaScript
547
star
16

d3-zoom

Pan and zoom SVG, HTML or Canvas using mouse or touch input.
JavaScript
495
star
17

d3-contour

Compute contour polygons using marching squares.
JavaScript
487
star
18

d3-interpolate

Interpolate numbers, colors, strings, arrays, objects, whatever!
JavaScript
482
star
19

d3-array

Array manipulation, ordering, searching, summarizing, etc.
JavaScript
452
star
20

d3-dsv

A parser and formatter for delimiter-separated values, such as CSV and TSV.
JavaScript
416
star
21

d3-color

Color spaces! RGB, HSL, Cubehelix, CIELAB, and more.
JavaScript
389
star
22

d3-drag

Drag and drop SVG, HTML or Canvas using mouse or touch input.
JavaScript
328
star
23

d3-voronoi

Compute the Voronoi diagram of a set of two-dimensional points.
JavaScript
250
star
24

d3-hexbin

Group two-dimensional points into hexagonal bins.
JavaScript
231
star
25

d3-time

A calculator for humanity鈥檚 peculiar conventions of time.
JavaScript
227
star
26

d3-quadtree

Two-dimensional recursive spatial subdivision.
JavaScript
225
star
27

d3-transition

Animated transitions for D3 selections.
JavaScript
219
star
28

d3-fetch

Convenient parsing for Fetch.
JavaScript
215
star
29

d3-axis

Human-readable reference marks for scales.
JavaScript
204
star
30

d3.github.com

The D3 website.
JavaScript
195
star
31

d3-path

Serialize Canvas path commands to SVG.
JavaScript
192
star
32

d3-timer

An efficient queue for managing thousands of concurrent animations.
JavaScript
159
star
33

d3-brush

Select a one- or two-dimensional region using the mouse or touch.
JavaScript
154
star
34

d3-3.x-api-reference

An archive of the D3 3.x API Reference.
153
star
35

d3-random

Generate random numbers from various distributions.
JavaScript
136
star
36

d3-chord

Visualizations relationships or network flow with a circular layout.
JavaScript
122
star
37

d3-tile

Compute the quadtree tiles to display in a rectangular viewport.
JavaScript
120
star
38

d3-collection

Handy data structures for elements keyed by string.
JavaScript
111
star
39

d3-request

A convenient alternative to XMLHttpRequest.
JavaScript
109
star
40

d3-geo-polygon

Clipping and geometric operations for spherical polygons.
JavaScript
102
star
41

d3-polygon

Geometric operations for two-dimensional polygons.
JavaScript
97
star
42

d3-require

A minimal, promise-based implementation to require asynchronous module definitions.
JavaScript
78
star
43

d3-selection-multi

Multi-value syntax for d3-selection and d3-transition.
JavaScript
75
star
44

d3-dispatch

Register named callbacks and call them with arguments.
JavaScript
75
star
45

versor

a home for Mike Bostock's versor.js
JavaScript
34
star
46

d3-bundler

DEPRECATED; use rollup/rollup.
JavaScript
34
star
47

d3-hsv

The HSV (Hue, Saturation, Value) color space.
JavaScript
26
star
48

d3-logo

D3 brand assets.
23
star
49

d3-cam16

A d3 implementation of the CIECAM16 color appearance model.
JavaScript
22
star
50

d3-hcg

The HCG (Hue, Chroma, Grayness) color space derived from the Munsell color system.
JavaScript
20
star
51

d3-scripts

Common scripts for D3 modules.
JavaScript
15
star
52

d3-hull

DEPRECATED; see d3-polygon鈥檚 hull function.
JavaScript
14
star
53

blur-benchmark

temporary benchmark for d3.blur implementations
JavaScript
2
star