Giter VIP home page Giter VIP logo

how-ago's Introduction

@vintl/how-ago

Relative time with @formatjs/intl made easy.

Supports: ESM only. Depends on @formatjs/intl. Support the author.

Summary

Intl.RelativeTimeFormat offers a way to localize relative time, like ‘1 day ago‘ or ‘in 1 year’. Unfortunately, it's very bare bones and does not perform any calculations, so you have to manually choose the unit of time and then amount of that unit.

This module provides an easy binding for @formatjs/intl to automatically calculate the most suitable unit based on formatting options and a time range, and then format the range with that unit.

Example

import { createIntl } from '@formatjs/intl'
import { createFormatter } from '@vintl/how-ago'

const intl = createIntl({ locale: 'en-US' })

const ago = createFormatter(intl)

const oneDay = 86400000 // ms

console.log(ago(Date.now() - oneDay))
// => "yesterday"

console.log(ago(Date.now() + oneDay * 2))
// => "in 2 days"

API

createFormatter

A function that creates a function to format relative time using the provided IntlShape.

Parameters:

  • intl (IntlShape) — IntlShape, which methods to format relative time or date will be used.

Returns: Formatter — Formatter function.

Formatter

A function that, given a specific time range or just a start date, calculates the time span between the two (if only the start date is provided, then the end date is assumed to be the time of the call). It then chooses the most suitable unit to display the span and returns a formatted string (e.g. ‘5 seconds ago’, ‘10 seconds ago’).

It uses Intl.RelativeTimeFormat under the hood, with the option numeric set to 'auto' by default. This means the span, such as +1 day, is formatted as ‘tomorrow’ and -1 day as ‘yesterday’. This default can be overridden through the provided options to match the original behaviour of Intl.RelativeTimeFormat, which is using 'always' as the default for numeric.

Parameters:

  • range (DateTimeRange) — Range for which time span is calculated.
  • options (FormatOptions) — Options for relative time formatter.

Returns: string — Formatted relative time or date used the most suitable unit or date formatting according to the provided options.

DateTimeRange

Describes a time range type which can be a value which is used as from, an array of values (from (1st element) and to (2nd element)) or an object with properties from and to which are also time range values.

If to is not omitted, then it is assumed to be the current time at the moment of interpretation.

DateTimeRangeValue

Describes a value within the time range that can be used as or converted to a timestamp. It must be either a string which can be used to instantiate a new Date object, a number containing UNIX time in milliseconds, or a Date object.

FormatOptions

Extends: Intl.RelativeTimeFormatOptions (omitted: localeMatcher) & { format?: string }.

Properties:

  • maximumUnit? (Intl.RelativeTimeFormatUnit or 'none')

    Maximum unit after which formatting to relative time should be abandoned and instead end date must be formatted using dateTimeOptions.

    If set to 'none', any time difference that does not exceed minimumUnit will be formatted in relative time.

    Default: 'none'.

  • minimumUnit? (Intl.RelativeTimeFormatUnit or 'none')

    Minimum unit before which formatting to relative time should be abandoned and instead end date must be formatted using dateTimeOptions.

    If set to 'none', any time difference that does not exceed maximumUnit will be formatted in relative time.

    Default: 'none'.

  • dateTimeOptions? (Intl.DateTimeFormatOptions (omitted: localeMatcher) & { format?: string })

    Options for datetime formatting when it reaches the cut-off unit.

    Default: { dateStyle: 'long', timeStyle: 'short' }

  • excludedUnits? (Array of Intl.RelativeTimeFormatUnit)

    Units to never use for relative time formatting.

    Default: ['quarter']

  • roundingMode? (RoundingMode)

    Rounding mode to use when the resulting duration is not an integer (e.g., 4.7 seconds).

    It is roughly equivalent to the roundingMode option for the Intl.NumberFormat API and accepts the following options:

    • ceil — round towards positive infinity.
    • floor — round towards negative infinity.
    • expand — round away from 0.
    • trunc — round towards 0.
    • halfCeil — round values below or at half-increment towards positive infinity, and values above away from 0.
    • halfFloor — round values below or at half-increment towards negative infinity, and values above away from 0.
    • halfExpand — round values above or at half-increment away from 0, and values below towards 0.
    • halfTrunc — round values below or at half-increment towards 0, and values above away from 0.
    • halfEven — round values at half-increment towards the nearest even value, values above it away from 0, and values below it towards 0.

    Default: 'trunc'.

  • unitRounding? (boolean)

    Whether to round to the nearest unit if the rounded duration goes above the threshold for the current unit.

    For example, if 59.7 minutes round to 60 minutes, and this option is enabled, the duration will be rounded to use hour units, thus returning "1 hour". Otherwise, the result of 60 minutes will be returned as is — "60 minutes".

    Default: true.

RoundingMode

String literal for one of the supported rounding modes.

Possible values: "ceil", "floor", "expand", "trunc", "halfCeil", "halfFloor", "halfExpand", "halfTrunc", "halfEven".

Acknowledgements

This implementation is based on the implementation from Modrinth's Omorphia project.

Credits

Made with 💜 by Brawaru. Released under MIT Licence.

Support me by donating

how-ago's People

Contributors

brawaru avatar renovate[bot] avatar

Stargazers

 avatar

Watchers

 avatar

Forkers

brawaru

how-ago's Issues

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Ignored or Blocked

These are blocked by an existing closed PR and will not be recreated unless you click a checkbox below.

Detected dependencies

github-actions
.github/workflows/release.yaml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/cache v4
.github/workflows/test-pr.yaml
  • actions/checkout v4
  • actions/setup-node v4
  • actions/cache v4
npm
package.json
  • intl-messageformat ^10.5.11
  • @nuxtjs/eslint-config-typescript ^12.1.0
  • @types/node ^18.19.31
  • eslint ^8.57.0
  • pathe ^1.1.2
  • prettier ^3.2.5
  • prettier-plugin-jsdoc ^1.3.0
  • semantic-release ^22.0.12
  • typescript ^5.4.5
  • unbuild ^2.0.0
  • vitest ^1.5.0
  • @formatjs/intl ^2.7.1
  • pnpm 9.0.6

  • Check this box to trigger a request for Renovate to run again on this repository

Custom unit scalars

After weeks the definitions of units becomes loose, since they are not fixed: month can be mean 28 days in financial sphere, or they can mean 30 or 31 days. Years sometimes can be 366 days.

Intl.RelativeTimeFormat does not care about that, it's your responsibility to provide the correct unit. However, we have our pre-defined units, so it would be great to be able to configure them to account for these non-standard cases.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.