{"id":10714,"library":"d3-time-format","title":"D3 Time Format","description":"d3-time-format is a core D3 module providing robust JavaScript utilities for formatting and parsing dates and times, inspired by the venerable `strftime` and `strptime` functions from the C standard library. Currently stable at version 4.1.0, this package typically releases new major versions for significant breaking changes or feature additions, while minor and patch releases address bug fixes and smaller enhancements. It enables developers to convert `Date` objects into human-readable, locale-specific strings and vice-versa, making it indispensable for data visualization and applications requiring precise time representation. A key differentiator is its deep integration within the D3 ecosystem, frequently used alongside D3 time scales, and its comprehensive support for various format specifiers and internationalization through locale definitions, which were notably enhanced in recent versions like 4.1.0 with additional exports and updates. It explicitly adopted modern JavaScript features like `type: module` in v4 and ES2015 in v3, signaling a commitment to contemporary development practices.","status":"active","version":"4.1.0","language":"javascript","source_language":"en","source_url":"https://github.com/d3/d3-time-format","tags":["javascript","d3","d3-module","time","format","strftime","strptime"],"install":[{"cmd":"npm install d3-time-format","lang":"bash","label":"npm"},{"cmd":"yarn add d3-time-format","lang":"bash","label":"yarn"},{"cmd":"pnpm add d3-time-format","lang":"bash","label":"pnpm"}],"dependencies":[{"reason":"Required for time interval functions like `timeSecond`, `timeMinute`, etc., commonly used with d3-time-format for multi-scale time formatting.","package":"d3-time","optional":false}],"imports":[{"note":"Since v4.0.0, d3-time-format is an ES Module. Use 'import' syntax. CommonJS 'require' will fail.","wrong":"const timeFormat = require('d3-time-format').timeFormat;","symbol":"timeFormat","correct":"import { timeFormat } from 'd3-time-format';"},{"note":"All core format/parse functions are named exports from the main package entry point.","wrong":"import timeParse from 'd3-time-format/timeParse';","symbol":"timeParse","correct":"import { timeParse } from 'd3-time-format';"},{"note":"Provides timezone-agnostic (UTC) formatting, distinct from `timeFormat` which uses local time.","symbol":"utcFormat","correct":"import { utcFormat } from 'd3-time-format';"},{"note":"For setting a global default locale, typically loaded asynchronously. This is a function that accepts a locale object.","wrong":"d3.timeFormatDefaultLocale = locale;","symbol":"timeFormatDefaultLocale","correct":"import { timeFormatDefaultLocale } from 'd3-time-format';"}],"quickstart":{"code":"import { timeFormat } from 'd3-time-format';\nimport { timeSecond, timeMinute, timeHour, timeDay, timeWeek, timeMonth, timeYear } from 'd3-time';\n\n// This quickstart demonstrates how to use d3-time-format to create a\n// multi-scale time formatter, which dynamically changes the date\n// format based on the time interval being displayed. This pattern is\n// commonly used in D3 visualizations for axis labels or tooltips\n// to provide appropriate granularity.\nconst formatMillisecond = timeFormat(\".%L\");\nconst formatSecond = timeFormat(\":%S\");\nconst formatMinute = timeFormat(\"%I:%M\");\nconst formatHour = timeFormat(\"%I %p\");\nconst formatDay = timeFormat(\"%a %d\");\nconst formatWeek = timeFormat(\"%b %d\");\nconst formatMonth = timeFormat(\"%B\");\nconst formatYear = timeFormat(\"%Y\");\n\nfunction multiFormat(date: Date): string {\n  return (timeSecond(date) < date ? formatMillisecond\n      : timeMinute(date) < date ? formatSecond\n      : timeHour(date) < date ? formatMinute\n      : timeDay(date) < date ? formatHour\n      : timeMonth(date) < date ? (timeWeek(date) < date ? formatDay : formatWeek)\n      : timeYear(date) < date ? formatMonth\n      : formatYear)(date);\n}\n\n// Example usage with various dates to show different formats\nconst now = new Date();\nconst dateInMs = new Date(now.getTime() - 500); // Less than a second ago\nconst dateInSeconds = new Date(now.getTime() - 15 * 1000); // 15 seconds ago\nconst dateInMinutes = new Date(now.getTime() - 5 * 60 * 1000); // 5 minutes ago\nconst dateInHours = new Date(now.getTime() - 3 * 60 * 60 * 1000); // 3 hours ago\nconst dateInDays = new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000); // 2 days ago\nconst dateInWeeks = new Date(now.getTime() - 3 * 7 * 24 * 60 * 60 * 1000); // 3 weeks ago\nconst dateInMonths = new Date(now.getTime() - 2 * 30 * 24 * 60 * 60 * 1000); // 2 months ago\nconst dateInYears = new Date(now.getTime() - 1 * 365 * 24 * 60 * 60 * 1000); // 1 year ago\n\nconsole.log(`Millisecond format: ${multiFormat(dateInMs)}`);\nconsole.log(`Second format: ${multiFormat(dateInSeconds)}`);\nconsole.log(`Minute format: ${multiFormat(dateInMinutes)}`);\nconsole.log(`Hour format: ${multiFormat(dateInHours)}`);\nconsole.log(`Day format: ${multiFormat(dateInDays)}`);\nconsole.log(`Week format: ${multiFormat(dateInWeeks)}`);\nconsole.log(`Month format: ${multiFormat(dateInMonths)}`);\nconsole.log(`Year format: ${multiFormat(dateInYears)}`);\n","lang":"typescript","description":"This demonstrates a multi-scale time formatter, dynamically adjusting date output based on the time interval, a common pattern in D3."},"warnings":[{"fix":"Migrate your project to use ES module `import` syntax or ensure your bundler (e.g., Webpack, Rollup) is configured to handle ESM. For Node.js, ensure you are running version 12+ and using 'type: module' in your package.json or saving files as .mjs.","message":"Version 4.0.0 adopted `type: module`, making it an ES Module (ESM) exclusively. It also raised the minimum Node.js requirement to v12 or higher. Projects using CommonJS (CJS) `require()` syntax will break.","severity":"breaking","affected_versions":">=4.0.0"},{"fix":"If supporting pre-ES2015 environments is necessary, either stick with d3-time-format 2.x or transpile your code using tools like Babel to downlevel ES2015+ syntax.","message":"Version 3.0.0 adopted ES2015 language features (e.g., `for-of`), dropping support for older browsers like Internet Explorer. Environments that do not support ES2015 will encounter runtime errors.","severity":"breaking","affected_versions":">=3.0.0"},{"fix":"Always ensure locale data is loaded and applied using `d3.timeFormatDefaultLocale(locale)` within an asynchronous context (e.g., `await` or `.then()`) before initializing and using time formatters that depend on the custom locale.","message":"Loading locale definitions (e.g., for `timeFormatDefaultLocale`) requires a network request (e.g., `d3.json`) and is asynchronous. Forgetting to wait for the locale to load before using formatters can lead to incorrect or default locale output.","severity":"gotcha","affected_versions":">=2.0.0"},{"fix":"For consistent and explicit handling of UTC dates, always use `utcFormat` and `utcParse`. If local time is desired, be aware of how different timezones and daylight saving times might affect parsing and formatting.","message":"The `timeFormat` and `timeParse` functions operate on local time by default, potentially leading to unexpected results if UTC handling is expected. `utcFormat` and `utcParse` should be used explicitly for UTC-based operations.","severity":"gotcha","affected_versions":">=2.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"fix":"Change `const { timeFormat } = require('d3-time-format');` to `import { timeFormat } from 'd3-time-format';`.","cause":"Attempting to use CommonJS `require()` syntax to import d3-time-format in an ES Module context or with d3-time-format v4+.","error":"ReferenceError: require is not defined"},{"fix":"Ensure your project's `package.json` has `\"type\": \"module\"` if you intend to use ESM, or configure your bundler (Webpack, Rollup) to handle ESM. Alternatively, use dynamic `import()` for CJS-only environments if absolutely necessary for a v4+ package.","cause":"Attempting to use ES Module `import` syntax in a CommonJS context without proper configuration, especially with d3-time-format v4+.","error":"SyntaxError: Cannot use import statement outside a module"},{"fix":"Double-check that the format `specifier` precisely matches the input date string. Ensure all necessary locale definitions are loaded if parsing a locale-specific string.","cause":"A `Date` object returned by `timeParse` is 'Invalid Date' because the input string did not match the provided specifier, or a custom locale was not loaded.","error":"Invalid Date"}],"ecosystem":"npm"}