Skip to content

d3-time-format

此模块提供了 C 标准库中经典的 strptimestrftime 函数的 JavaScript 近似实现,可用于以各种特定于语言环境的表示形式解析或格式化 dates。要格式化日期,请根据说明符(包含所需格式指令的字符串,由 % 指示)创建 formatter;然后将日期传递给格式化程序,格式化程序返回一个字符串。例如,要将当前日期转换为人类可读的字符串:

¥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:

js
const formatTime = d3.utcFormat("%B %d, %Y");
formatTime(new Date()); // "May 31, 2023"

同样,要将字符串转换回日期,请创建一个 parser

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

js
const parseTime = d3.utcParse("%B %d, %Y");
parseTime("June 30, 2015"); // 2023-05-31

你也可以实现更复杂的条件时间格式。例如,这是一个使用 时间间隔 的多尺度时间格式:

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

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

function multiFormat(date) {
  return (d3.utcSecond(date) < date ? formatMillisecond
      : d3.utcMinute(date) < date ? formatSecond
      : d3.utcHour(date) < date ? formatMinute
      : d3.utcDay(date) < date ? formatHour
      : d3.utcMonth(date) < date ? (d3.utcWeek(date) < date ? formatDay : formatWeek)
      : d3.utcYear(date) < date ? formatMonth
      : formatYear)(date);
}

此模块被 D3 时间尺度 用于生成易于理解的刻度。

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

另请参阅 date.toLocaleString

¥Also see date.toLocaleString.

timeFormat(specifier)

js
d3.timeFormat("%b %d")

默认语言环境locale.format 的别名。

¥An alias for locale.format on the default locale.

timeParse(specifier)

js
d3.timeParse("%b %d")

默认语言环境locale.parse 的别名。

¥An alias for locale.parse on the default locale.

utcFormat(specifier)

js
d3.utcFormat("%b %d")

默认语言环境locale.utcFormat 的别名。

¥An alias for locale.utcFormat on the default locale.

utcParse(specifier)

js
d3.utcParse("%b %d")

默认语言环境locale.utcParse 的别名。

¥An alias for locale.utcParse on the default locale.

isoFormat

js
d3.isoFormat(new Date()) // "2023-05-31T18:17:36.788Z"

源代码 · 完整的 ISO 8601 UTC 时间格式化程序。如果可用,此方法将使用 Date.toISOString 进行格式化。

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

isoParse

js
d3.isoParse("2023-05-31T18:17:36.788Z")

源代码 · 完整的 ISO 8601 UTC 时间解析器。如果可用,此方法将使用 日期构造函数 解析字符串。如果你依赖于根据 ISO 8601 对输入格式进行严格验证,则应构建一个 UTC 解析函数

¥Source · 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:

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

locale.format(specifier) {#locale_format}

js
d3.timeFormat("%b %d")

源代码 · 返回给定字符串说明符的新格式化程序。说明符字符串可以包含以下指令:

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

  • %a - 缩写的星期名称。*

    ¥%a - abbreviated weekday name.*

  • %A - 完整的星期名称。*

    ¥%A - full weekday name.*

  • %b - 缩写的月份名称。*

    ¥%b - abbreviated month name.*

  • %B - 完整的月份名称。*

    ¥%B - full month name.*

  • %c - 区域设置的日期和时间,例如 %x, %X.*

    ¥%c - the locale’s date and time, such as %x, %X.*

  • %d - 以零填充的十进制数 [01,31] 表示月份中的日期。

    ¥%d - zero-padded day of the month as a decimal number [01,31].

  • %e - 以空格填充的十进制数 [1,31] 表示月份中的日期;相当于 %_d

    ¥%e - space-padded day of the month as a decimal number [ 1,31]; equivalent to %_d.

  • %f - 微秒,十进制数 [000000, 999999]。

    ¥%f - microseconds as a decimal number [000000, 999999].

  • %g - ISO 8601 以十进制数表示的不带世纪的基于周的年份 [00,99]。

    ¥%g - ISO 8601 week-based year without century as a decimal number [00,99].

  • %G - ISO 8601 以十进制数表示的基于周且带世纪的年份。

    ¥%G - ISO 8601 week-based year with century as a decimal number.

  • %H - 小时(24 小时制)表示为十进制数 [00,23]。

    ¥%H - hour (24-hour clock) as a decimal number [00,23].

  • %I - 小时(12 小时制)表示为十进制数 [01,12]。

    ¥%I - hour (12-hour clock) as a decimal number [01,12].

  • %j - 以十进制数 [001,366] 表示一年中的某天。

    ¥%j - day of the year as a decimal number [001,366].

  • %m - 月份为十进制数 [01,12]。

    ¥%m - month as a decimal number [01,12].

  • %M - 分钟,十进制数 [00,59]。

    ¥%M - minute as a decimal number [00,59].

  • %L - 毫秒,十进制数 [000, 999]。

    ¥%L - milliseconds as a decimal number [000, 999].

  • %p - 上午或下午。*

    ¥%p - either AM or PM.*

  • %q - 将一年中的某个季度表示为十进制数 [1,4]。

    ¥%q - quarter of the year as a decimal number [1,4].

  • %Q - 自 UNIX 纪元以来的毫秒数。

    ¥%Q - milliseconds since UNIX epoch.

  • %s - 自 UNIX 纪元以来的秒数。

    ¥%s - seconds since UNIX epoch.

  • %S - 以十进制数 [00,61] 表示秒。

    ¥%S - second as a decimal number [00,61].

  • %u - 基于星期一 (ISO 8601) 的星期,以十进制数 [1,7] 表示。

    ¥%u - Monday-based (ISO 8601) weekday as a decimal number [1,7].

  • %U - 以十进制数 [00,53] 表示一年中基于星期日的周数。

    ¥%U - Sunday-based week of the year as a decimal number [00,53].

  • %V - ISO 8601 以十进制数表示的一年中的周数 [01, 53]。

    ¥%V - ISO 8601 week of the year as a decimal number [01, 53].

  • %w - 以十进制数 [0,6] 表示基于星期日的星期几。

    ¥%w - Sunday-based weekday as a decimal number [0,6].

  • %W - 基于星期一的一年中的周,以十进制数 [00,53] 表示。

    ¥%W - Monday-based week of the year as a decimal number [00,53].

  • %x - 区域设置的日期,例如 %-m/%-d/%Y.*

    ¥%x - the locale’s date, such as %-m/%-d/%Y.*

  • %X - 区域设置的时间,例如 %-I:%M:%S %p.*

    ¥%X - the locale’s time, such as %-I:%M:%S %p.*

  • %y - 不带世纪的年份,以十进制数表示 [00,99]。

    ¥%y - year without century as a decimal number [00,99].

  • %Y - 带世纪的年份,以十进制数表示,例如 1999

    ¥%Y - year with century as a decimal number, such as 1999.

  • %Z - 时区偏移量,例如 -0700-07:00-07Z

    ¥%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.

对于 %U,新年中第一个星期日之前的所有日子都被视为第 0 周。对于 %W,新年中第一个星期一之前的所有日子都被视为第 0 周。周数使用 interval.count 计算。例如,2015-52 和 2016-00 代表 2015 年 12 月 28 日星期一,而 2015-53 和 2016-01 代表 2016 年 1 月 4 日星期一。这与 ISO 周日期 规范 (%V) 不同,后者使用了更复杂的定义!

¥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!

对于 %V%g%G,根据 strftime 手册页

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

在此系统中,周从星期一开始,从 01(第一周)到 52 或 53(最后一周)进行编号。第 1 周是新年内有四天或四天以上的第一周(或者,同义地,第 01 周是:一年中第一个包含星期四的周;或者,包含 1 月 4 日的周)。如果 ISO 周数属于上一年或下一年,则使用该年份。

¥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

如果未指定填充修饰符,则除 %e 之外的所有指令的默认值均为 0%e 默认为 _。(在 strftime 和 strptime 的某些实现中,指令可能包含可选的字段宽度或精度;此功能尚未实现。)

¥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.)

返回的函数格式化指定的 date,并返回相应的字符串。

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

js
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) {#locale_parse}

js
d3.timeParse("%b %d")

源代码 · 返回给定字符串说明符的新解析器。说明符字符串可以包含与 locale.format 相同的指令。%d%e 指令在解析时被视为等效指令。

¥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.

返回的函数解析指定的字符串,返回相应的 date;如果字符串无法根据此格式的说明符解析,则返回 null。解析是严格的:如果指定的 string 与关联的说明符不完全匹配,则此方法返回 null。例如,如果关联的说明符是 %Y-%m-%dT%H:%M:%SZ,则字符串 "2011-07-01T19:15:28Z" 将按预期解析,但 "2011-07-01T19:15:28""2011-07-01 19:15:28""2011-07-01" 将返回 null。(请注意,此处的文字 Z 与时区偏移指令 %Z 不同。)如果需要更灵活的解析器,请依次尝试多种格式,直到其中一种返回非空值。

¥The returned function parses a specified string, returning the corresponding date or null if the string could not be parsed according to this format’s 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) {#locale_utcFormat}

js
d3.utcFormat("%b %d")

源代码 · 等同于 locale.format,但所有指令都被解释为 协调世界时 (UTC) 而不是当地时间。

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

locale.utcParse(specifier) {#locale_utcParse}

js
d3.utcParse("%b %d")

源代码 · 等同于 locale.parse,但所有指令都被解释为 协调世界时 (UTC) 而不是当地时间。

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

timeFormatLocale(definition)

js
const enUs = d3.timeFormatLocale({
  dateTime: "%x, %X",
  date: "%-m/%-d/%Y",
  time: "%-I:%M:%S %p",
  periods: ["AM", "PM"],
  days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});

源代码 · 返回一个指定定义的语言环境对象,该对象包含 locale.formatlocale.parselocale.utcFormatlocale.utcParse 方法。定义必须包含以下属性:

¥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 - 日期和时间 (%c) 格式说明符(例如 "%a %b %e %X %Y")。

    ¥dateTime - the date and time (%c) format specifier (e.g., "%a %b %e %X %Y").

  • date - 日期 (%x) 格式说明符(例如 "%m/%d/%Y")。

    ¥date - the date (%x) format specifier (e.g., "%m/%d/%Y").

  • time - 时间 (%X) 格式说明符(例如"%H:%M:%S")。

    ¥time - the time (%X) format specifier (e.g., "%H:%M:%S").

  • periods - 上午。以及下午。等价于(例如 ["AM", "PM"])。

    ¥periods - the A.M. and P.M. equivalents (e.g., ["AM", "PM"]).

  • days - 星期几的全名,从星期日开始。

    ¥days - the full names of the weekdays, starting with Sunday.

  • shortDays - 工作日的缩写,从周日开始。

    ¥shortDays - the abbreviated names of the weekdays, starting with Sunday.

  • months - 月份的全名(从一月开始)。

    ¥months - the full names of the months (starting with January).

  • shortMonths - 月份的缩写(从一月开始)。

    ¥shortMonths - the abbreviated names of the months (starting with January).

timeFormatDefaultLocale(definition)

js
const enUs = d3.timeFormatDefaultLocale({
  dateTime: "%x, %X",
  date: "%-m/%-d/%Y",
  time: "%-I:%M:%S %p",
  periods: ["AM", "PM"],
  days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"],
  shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"],
  months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
  shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
});

源代码 · 等同于 d3.timeFormatLocale,但它还将 d3.timeFormatd3.timeParsed3.utcFormatd3.utcParse 重新定义为新语言环境的 locale.formatlocale.parselocale.utcFormatlocale.utcParse。如果你未设置默认语言环境,则默认为 U.S.英语

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