UNPKG

13.4 kBMarkdownView Raw
1# d3-time-format
2
3This module provides a JavaScript implementation of the venerable [strptime](http://pubs.opengroup.org/onlinepubs/009695399/functions/strptime.html) and [strftime](http://pubs.opengroup.org/onlinepubs/007908799/xsh/strftime.html) functions from the C standard library, and can be used to parse or format [dates](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) in a variety of locale-specific representations. To format a date, create a [formatter](#locale_format) 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:
4
5```js
6const formatTime = d3.timeFormat("%B %d, %Y");
7formatTime(new Date); // "June 30, 2015"
8```
9
10Likewise, to convert a string back to a date, create a [parser](#locale_parse):
11
12```js
13const parseTime = d3.timeParse("%B %d, %Y");
14parseTime("June 30, 2015"); // Tue Jun 30 2015 00:00:00 GMT-0700 (PDT)
15```
16
17You can implement more elaborate conditional time formats, too. For example, here’s a [multi-scale time format](https://bl.ocks.org/mbostock/4149176) using [time intervals](https://github.com/d3/d3-time):
18
19```js
20const formatMillisecond = d3.timeFormat(".%L"),
21 formatSecond = d3.timeFormat(":%S"),
22 formatMinute = d3.timeFormat("%I:%M"),
23 formatHour = d3.timeFormat("%I %p"),
24 formatDay = d3.timeFormat("%a %d"),
25 formatWeek = d3.timeFormat("%b %d"),
26 formatMonth = d3.timeFormat("%B"),
27 formatYear = d3.timeFormat("%Y");
28
29function multiFormat(date) {
30 return (d3.timeSecond(date) < date ? formatMillisecond
31 : d3.timeMinute(date) < date ? formatSecond
32 : d3.timeHour(date) < date ? formatMinute
33 : d3.timeDay(date) < date ? formatHour
34 : d3.timeMonth(date) < date ? (d3.timeWeek(date) < date ? formatDay : formatWeek)
35 : d3.timeYear(date) < date ? formatMonth
36 : formatYear)(date);
37}
38```
39
40This module is used by D3 [time scales](https://github.com/d3/d3-scale/blob/main/README.md#time-scales) to generate human-readable ticks.
41
42## Installing
43
44If you use npm, `npm install d3-time-format`. You can also download the [latest release on GitHub](https://github.com/d3/d3-time-format/releases/latest). For vanilla HTML in modern browsers, import d3-time-format from Skypack:
45
46```html
47<script type="module">
48
49import {timeFormat} from "https://cdn.skypack.dev/d3-time-format@4";
50
51const format = timeFormat("%x");
52
53</script>
54```
55
56For legacy environments, you can load d3-time-format’s UMD bundle from an npm-based CDN such as jsDelivr; a `d3` global is exported:
57
58```html
59<script src="https://cdn.jsdelivr.net/npm/d3-array@3"></script>
60<script src="https://cdn.jsdelivr.net/npm/d3-time@3"></script>
61<script src="https://cdn.jsdelivr.net/npm/d3-time-format@4"></script>
62<script>
63
64const format = d3.timeFormat("%x");
65
66</script>
67
68Locale files are published to npm and can be loaded using [d3.json](https://github.com/d3/d3-fetch/blob/main/README.md#json). For example, to set Russian as the default locale:
69
70```js
71d3.json("https://cdn.jsdelivr.net/npm/d3-time-format@3/locale/ru-RU.json").then(locale => {
72 d3.timeFormatDefaultLocale(locale);
73
74 const format = d3.timeFormat("%c");
75
76 console.log(format(new Date)); // понедельник, 5 декабря 2016 г. 10:31:59
77});
78```
79
80## API Reference
81
82<a name="timeFormat" href="#timeFormat">#</a> d3.<b>timeFormat</b>(<i>specifier</i>) · [Source](https://github.com/d3/d3-time-format/blob/main/src/defaultLocale.js)
83
84An alias for [*locale*.format](#locale_format) on the [default locale](#timeFormatDefaultLocale).
85
86<a name="timeParse" href="#timeParse">#</a> d3.<b>timeParse</b>(<i>specifier</i>) · [Source](https://github.com/d3/d3-time-format/blob/main/src/defaultLocale.js)
87
88An alias for [*locale*.parse](#locale_parse) on the [default locale](#timeFormatDefaultLocale).
89
90<a name="utcFormat" href="#utcFormat">#</a> d3.<b>utcFormat</b>(<i>specifier</i>) · [Source](https://github.com/d3/d3-time-format/blob/main/src/defaultLocale.js)
91
92An alias for [*locale*.utcFormat](#locale_utcFormat) on the [default locale](#timeFormatDefaultLocale).
93
94<a name="utcParse" href="#utcParse">#</a> d3.<b>utcParse</b>(<i>specifier</i>) · [Source](https://github.com/d3/d3-time-format/blob/main/src/defaultLocale.js)
95
96An alias for [*locale*.utcParse](#locale_utcParse) on the [default locale](#timeFormatDefaultLocale).
97
98<a name="isoFormat" href="#isoFormat">#</a> d3.<b>isoFormat</b> · [Source](https://github.com/d3/d3-time-format/blob/main/src/isoFormat.js)
99
100The full [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) UTC time formatter. Where available, this method will use [Date.toISOString](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toISOString) to format.
101
102<a name="isoParse" href="#isoParse">#</a> d3.<b>isoParse</b> · [Source](https://github.com/d3/d3-time-format/blob/main/src/isoParse.js)
103
104The full [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) UTC time parser. Where available, this method will use the [Date constructor](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date) to parse strings. If you depend on strict validation of the input format according to ISO 8601, you should construct a [UTC parser function](#utcParse):
105
106```js
107const strictIsoParse = d3.utcParse("%Y-%m-%dT%H:%M:%S.%LZ");
108```
109
110<a name="locale_format" href="#locale_format">#</a> <i>locale</i>.<b>format</b>(<i>specifier</i>) · [Source](https://github.com/d3/d3-time-format/blob/main/src/locale.js)
111
112Returns a new formatter for the given string *specifier*. The specifier string may contain the following directives:
113
114* `%a` - abbreviated weekday name.*
115* `%A` - full weekday name.*
116* `%b` - abbreviated month name.*
117* `%B` - full month name.*
118* `%c` - the locale’s date and time, such as `%x, %X`.*
119* `%d` - zero-padded day of the month as a decimal number [01,31].
120* `%e` - space-padded day of the month as a decimal number [ 1,31]; equivalent to `%_d`.
121* `%f` - microseconds as a decimal number [000000, 999999].
122* `%g` - ISO 8601 week-based year without century as a decimal number [00,99].
123* `%G` - ISO 8601 week-based year with century as a decimal number.
124* `%H` - hour (24-hour clock) as a decimal number [00,23].
125* `%I` - hour (12-hour clock) as a decimal number [01,12].
126* `%j` - day of the year as a decimal number [001,366].
127* `%m` - month as a decimal number [01,12].
128* `%M` - minute as a decimal number [00,59].
129* `%L` - milliseconds as a decimal number [000, 999].
130* `%p` - either AM or PM.*
131* `%q` - quarter of the year as a decimal number [1,4].
132* `%Q` - milliseconds since UNIX epoch.
133* `%s` - seconds since UNIX epoch.
134* `%S` - second as a decimal number [00,61].
135* `%u` - Monday-based (ISO 8601) weekday as a decimal number [1,7].
136* `%U` - Sunday-based week of the year as a decimal number [00,53].
137* `%V` - ISO 8601 week of the year as a decimal number [01, 53].
138* `%w` - Sunday-based weekday as a decimal number [0,6].
139* `%W` - Monday-based week of the year as a decimal number [00,53].
140* `%x` - the locale’s date, such as `%-m/%-d/%Y`.*
141* `%X` - the locale’s time, such as `%-I:%M:%S %p`.*
142* `%y` - year without century as a decimal number [00,99].
143* `%Y` - year with century as a decimal number, such as `1999`.
144* `%Z` - time zone offset, such as `-0700`, `-07:00`, `-07`, or `Z`.
145* `%%` - a literal percent sign (`%`).
146
147Directives marked with an asterisk (\*) may be affected by the [locale definition](#locales).
148
149For `%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](https://github.com/d3/d3-time/blob/main/README.md#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](https://en.wikipedia.org/wiki/ISO_week_date) specification (`%V`), which uses a more complicated definition!
150
151For `%V`,`%g` and `%G`, per the [strftime man page](http://man7.org/linux/man-pages/man3/strftime.3.html):
152
153> 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.
154
155The `%` sign indicating a directive may be immediately followed by a padding modifier:
156
157* `0` - zero-padding
158* `_` - space-padding
159* `-` - disable padding
160
161If 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.)
162
163The returned function formats a specified *[date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date)*, returning the corresponding string.
164
165```js
166const formatMonth = d3.timeFormat("%B"),
167 formatDay = d3.timeFormat("%A"),
168 date = new Date(2014, 4, 1); // Thu May 01 2014 00:00:00 GMT-0700 (PDT)
169
170formatMonth(date); // "May"
171formatDay(date); // "Thursday"
172```
173
174<a name="locale_parse" href="#locale_parse">#</a> <i>locale</i>.<b>parse</b>(<i>specifier</i>) · [Source](https://github.com/d3/d3-time-format/blob/main/src/locale.js)
175
176Returns a new parser for the given string *specifier*. The specifier string may contain the same directives as [*locale*.format](#locale_format). The `%d` and `%e` directives are considered equivalent for parsing.
177
178The returned function parses a specified *string*, returning the corresponding [date](https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date) or null if the string could not be parsed according to this format’s specifier. Parsing is strict: if the specified <i>string</i> 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.
179
180<a name="locale_utcFormat" href="#locale_utcFormat">#</a> <i>locale</i>.<b>utcFormat</b>(<i>specifier</i>) · [Source](https://github.com/d3/d3-time-format/blob/main/src/locale.js)
181
182Equivalent to [*locale*.format](#locale_format), except all directives are interpreted as [Coordinated Universal Time (UTC)](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) rather than local time.
183
184<a name="locale_utcParse" href="#locale_utcParse">#</a> <i>locale</i>.<b>utcParse</b>(<i>specifier</i>) · [Source](https://github.com/d3/d3-time-format/blob/main/src/locale.js)
185
186Equivalent to [*locale*.parse](#locale_parse), except all directives are interpreted as [Coordinated Universal Time (UTC)](https://en.wikipedia.org/wiki/Coordinated_Universal_Time) rather than local time.
187
188### Locales
189
190<a name="timeFormatLocale" href="#timeFormatLocale">#</a> d3.<b>timeFormatLocale</b>(<i>definition</i>) · [Source](https://github.com/d3/d3-time-format/blob/main/src/locale.js)
191
192Returns a *locale* object for the specified *definition* with [*locale*.format](#locale_format), [*locale*.parse](#locale_parse), [*locale*.utcFormat](#locale_utcFormat), [*locale*.utcParse](#locale_utcParse) methods. The *definition* must include the following properties:
193
194* `dateTime` - the date and time (`%c`) format specifier (<i>e.g.</i>, `"%a %b %e %X %Y"`).
195* `date` - the date (`%x`) format specifier (<i>e.g.</i>, `"%m/%d/%Y"`).
196* `time` - the time (`%X`) format specifier (<i>e.g.</i>, `"%H:%M:%S"`).
197* `periods` - the A.M. and P.M. equivalents (<i>e.g.</i>, `["AM", "PM"]`).
198* `days` - the full names of the weekdays, starting with Sunday.
199* `shortDays` - the abbreviated names of the weekdays, starting with Sunday.
200* `months` - the full names of the months (starting with January).
201* `shortMonths` - the abbreviated names of the months (starting with January).
202
203For an example, see [Localized Time Axis II](https://bl.ocks.org/mbostock/805115ebaa574e771db1875a6d828949).
204
205<a name="timeFormatDefaultLocale" href="#timeFormatDefaultLocale">#</a> d3.<b>timeFormatDefaultLocale</b>(<i>definition</i>) · [Source](https://github.com/d3/d3-time-format/blob/main/src/defaultLocale.js)
206
207Equivalent to [d3.timeFormatLocale](#timeFormatLocale), except it also redefines [d3.timeFormat](#timeFormat), [d3.timeParse](#timeParse), [d3.utcFormat](#utcFormat) and [d3.utcParse](#utcParse) to the new locale’s [*locale*.format](#locale_format), [*locale*.parse](#locale_parse), [*locale*.utcFormat](#locale_utcFormat) and [*locale*.utcParse](#locale_utcParse). If you do not set a default locale, it defaults to [U.S. English](https://github.com/d3/d3-time-format/blob/main/locale/en-US.json).
208
209For an example, see [Localized Time Axis](https://bl.ocks.org/mbostock/6f1cc065d4d172bcaf322e399aa8d62f).