Giter Club home page Giter Club logo

intl-unofficial-duration-unit-format's Introduction

Intl DurationUnitFormat

Format time duration in quantities of units such as years, months, days, hours, minutes and seconds.

Overview

The goal of this project is to provide a way to format time durations (like 1 minute 30 seconds) since the standards don't provide a way to do it.

ECMAScript Internationalization has a long-standing open issue to provide an Intl.DurationFormat API that can accommodate time duration use cases, but as of February 2020 the proposal is still at Stage 1.

This project does its best at creating a DurationFormat implementation that resembles other standard APIs, but only work with time durations.

I'm not in any way part of the standardization process, that's why this package is -unofficial-.

Use cases

  1. Natural language time: 1 minute 20 seconds
  2. Timers: 01:20
  3. Short formats 1 hr 2 min 30 sec or 1h 2m 30s

Usage

const duration = new DurationUnitFormat(locales, options);
const parts = duration.formatToParts(90);

/*
parts = [
  { type: 'minute', value: '1' },
  { type: 'literal', value: ' ' },
  { type: 'unit', value: 'minute' },
  { type: 'second', value: '30' },
  { type: 'literal', value: ' ' },
  { type: 'unit', value: 'seconds' },
];
 */

Installation

npm i intl-unofficial-duration-unit-format

This package depends on intl-messageformat which is listed in peerDependencies.

intl-messageformat itself depends on the global Intl object. Refer to intl-messageformat README on how to set it up correctly on node.js or in the browser.

Webpack / Parcel / Rollup / ....

All modern bundlers allow you to import npm libraries

import DurationUnitFormat from 'intl-unofficial-duration-unit-format';

Public API

DurationUnitFormat constructor

To create a duration unit to format, use the DurationUnitFormat constructor, it takes two parameters:

  1. locales: String | Array<String> A string with a BCP 47 language tag, or an array of such strings. For more details check this.
  2. options: Object An optional configuration object. Refer to Options for additional details.

formatToParts(number)

Once the duration object is created with duration = new DurationUnitFormat(), you can call formatToParts passing a numeric value.

number must be expressed in seconds, so a value of 60 corresponds to 1 minute.

Options

style

One of

  1. DurationUnitFormat.styles.LONG or just long for long format time (1 minute 30 seconds)
  2. DurationUnitFormat.styles.SHORT or just short for short format time (1 min 30 sec)
  3. DurationUnitFormat.styles.NARROW or just narrow for narrow format time (1m 30s)
  4. DurationUnitFormat.styles.TIMER for timers (1:30)
  5. DurationUnitFormat.styles.CUSTOM for custom formats (1 minute 30 seconds)

The default is LONG.

When the style is TIMER numbers are padded and different default formats are applied.

The options formatDuration and formatUnits only apply when the style is CUSTOM.

Given the input of 3600 (1 hour), it'll generate

style format Output
CUSTOM undefined (defaults to {seconds}) 3600 seconds
CUSTOM {minutes} {seconds} 60 minutes
CUSTOM {hour} {minutes} {seconds} 1 hour
TIMER undefined (defaults to {minutes}:{seconds}) 60:00
TIMER {seconds}s 3600s
TIMER {hour}:{minutes}:{seconds} 1:00:00
TIMER {days}d {hour}:{minutes}:{seconds} 0d 01:00:00
LONG undefined (defaults to {seconds}) 3600 seconds
LONG {minutes} {seconds} 60 minutes
LONG {hour} {minutes} {seconds} 1 hour
SHORT undefined (defaults to {seconds}) 3600 sec
SHORT {minutes} {seconds} 60 min
SHORT {hour} {minutes} {seconds} 1 hr
NARROW undefined (defaults to {seconds}) 3600s
NARROW {minutes} {seconds} 60m
NARROW {hour} {minutes} {seconds} 1h

As shown from the examples, when TIMER is used

  1. empty units are kept and rendered as 00 or 0 if they're the highest unit in the format. Empty units in CUSTOM are discarded.
  2. values are padded to at least 2 digits

Note that on Node.js 10.x, the default implementation of Intl.NumberFormat does not support styles, so you need to use the @formatjs/intl-unified-numberformat polyfill.

format

Defines the format of the output string. Default to {seconds}.

It can be any string containing any of the placeholders {days}, {hours}, {minutes}, {seconds} or any other literal. The format of the placeholders can be customized by formatDuration.

Given the input of 3661 (1 hour, 1 minute and 1 second), it'll generate

format Output
{seconds} 3661 seconds
{minutes} {seconds} 61 minutes 1 second
{minutes} and {seconds} 61 minutes and 1 second
{hours} {minutes} {seconds} 1 hour 1 minute 1 second
{hours} {minutes} 1 hour 1 minute
{hours} 1 hour
{hours} 1 hour
{days} 0 days

formatDuration

Defines the format of the output placeholders. Default to {value} {unit}.

It can be any string containing {value}, {unit} or any other literal. {value} corresponds to the numeric value (1), while {unit} is the time unit (minute, second).

Given the input of 1, it'll generate

formatDuration Output
{value} {unit} 1 second
{value}{unit} 1second
{unit}: {value} second: 1

formatUnits

Defines the format and localization of each placeholder's {unit}. Defaults to the object

{
  [DurationUnitFormat.units.DAY]: '{value, plural, one {day} other {days}}',
  [DurationUnitFormat.units.HOUR]: '{value, plural, one {hour} other {hours}}',
  [DurationUnitFormat.units.MINUTE]: '{value, plural, one {minute} other {minutes}}',
  [DurationUnitFormat.units.SECOND]: '{value, plural, one {second} other {seconds}}',
}

The object key must be one of the possible units, and the value is a string using the ICU format defined in intl-messageformat.

Given the input of 1, it'll generate

formatUnits[DurationUnitFormat.units.SECOND] Output
{value, plural, one {second} other {seconds}} second
{value, plural, other {็ง’}} ็ง’
s s

round

Whether or not to round results when smaller units are missing. Default to false.

Given the input of 30 and the format {minutes}

round Output
false 0 minutes
true 1 minute

intl-unofficial-duration-unit-format's People

Contributors

brettz9 avatar dependabot[bot] avatar khmm12 avatar piuccio avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

intl-unofficial-duration-unit-format's Issues

Custom format for TIMER style

Is it possible to have a double-digit hour without using the day for the TIMER style ?
When I use format: '{hour}:{minutes}' together with style TIMER, I get 1:43 but I would like 01:43

Thanks :)

NPM version out of date?

Hello! It looks like the version coming in via npm is out of date as it has the NARROW style commented out. Can we get an updated version released?

Support `hideZeroValues` and `fields`

Currently, if the numbers are too low (e.g., less than an hour), there is no way to have 0 values hidden. This may complicate things with a formatter because if there are no hours and {hours}, {minutes} is chosen, one will be left with , 20 s or such. I think therefore that the hideZeroValues and fields options are important for such cases in controlling what will be shown.

Account for Android Hermes Limitation

Hi! ๐Ÿ‘‹

Firstly, thanks for your work on this project! ๐Ÿ™‚

Today I used patch-package to patch [email protected] for the project I'm working on.

Some versions of Hermes can return literal values so this fix accounts for that

Here is the diff that solved my problem:

diff --git a/node_modules/intl-unofficial-duration-unit-format/index.js b/node_modules/intl-unofficial-duration-unit-format/index.js
index 3473329..704ff8d 100644
--- a/node_modules/intl-unofficial-duration-unit-format/index.js
+++ b/node_modules/intl-unofficial-duration-unit-format/index.js
@@ -107,7 +107,8 @@ DurationUnitFormat.prototype._formatValue = function (number) {
 
 DurationUnitFormat.prototype._trimOutput = function (result, parts) {
   const trimmed = trim(result, this.isTimer);
-  if (!trimmed.find((_) => _.type !== 'literal')) {
+  // Accounts for Android Hermes limitation https://hermesengine.dev/docs/intl/#android-10-and-older-sdk--30
+  if (!trimmed.find((_) => _.type !== 'literal' || _.value.trim() !== '')) {
     // if everything cancels out and there are only literals,
     // then return 0 on the lowest available unit
     const minUnit = [

This issue body was partially generated by patch-package.

[Question] Is there a way to simply output the expected formatted string without needing to use the intermediate formatToParts output?

In the following basic example:

import DurationUnitFormat from 'intl-unofficial-duration-unit-format';


const duration = new DurationUnitFormat(
  [
    'en-GB',
    'en',
  ],
  {
    style: DurationUnitFormat.styles.TIMER,
  },
);

// currently
console.log(duration.formatToParts(3500));    // [{"type":"minute","value":"58"},{"type":"literal","value":":"},{"type":"second","value":"20"}]

// ideal
console.log(duration.format(3500));    // '58:20'

Is there a way to get the above ideal output, without having to explicitly handle the formatToParts() returned object?

I can do it in the following way:

duration.formatToParts(3500).map(({ type, value }) => value).join('')

...but this feels inelegant, and doesn't match my expectations from using the other similar Intl.DateTimeFormat, Intl.NumberFormat etc, all of which have a format() method.

Package has been ignored because it contains invalid configuration

Hello,

When building my app on android or IOS with react-native, I see this log warning:
warn Package intl-unofficial-duration-unit-format has been ignored because it contains invalid configuration. Reason: Package subpath './package.json' is not defined by "exports" in /Users/I543492/Documents/emobility/ev-mobile/node_modules/intl-unofficial-duration-unit-format/package.json

Do you have any hints ?

Also when running the test suite on GitHub, I see this error:
โ— Test suite failed to run Cannot find module 'intl-messageformat' from 'node_modules/intl-unofficial-duration-unit-format/dist/cjs/duration-unit-format.cjs.js' Require stack: node_modules/intl-unofficial-duration-unit-format/dist/cjs/duration-unit-format.cjs.js src/I18n/I18nManager.tsx __tests__/I18nManagerTests.tsx at Resolver.resolveModule (node_modules/jest-runtime/node_modules/jest-resolve/build/index.js:306:[11](https://github.com/sap-labs-france/ev-mobile/runs/5406296843?check_suite_focus=true#step:7:11)) at Object.<anonymous> (node_modules/intl-unofficial-duration-unit-format/dist/cjs/duration-unit-format.cjs.js:3:25)

[Bug] German translations wrong NARROW style

When using the following options with de locale:
durationFormatOptions = {style: DurationUnitFormat.styles.NARROW, format: '{day} {hour}'}
days and hours abbreviations are in english i.e d and h instead of T and Std

[Update] it appears to also be in english for czech

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.