question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

How to get precise second(s) in `relativeTime` plugin?

See original GitHub issue

Describe the bug https://github.com/iamkun/dayjs/blob/dev/src/plugin/relativeTime/index.js#L8 All seconds displays a few seconds

Expected behavior I want to display 1 second, 2 seconds...

Information

  • Day.js Version: 1.8.22

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:2
  • Comments:11 (11 by maintainers)

github_iconTop GitHub Comments

1reaction
iamkuncommented, Mar 12, 2020

Looks sweet. 😁

Let me think for a while.

1reaction
JounQincommented, Mar 12, 2020

@iamkun How about add a strict option for relativeTime plugin?

// based on https://github.com/iamkun/dayjs/blob/dev/src/plugin/relativeTime/index.js
/// <reference path="./relative-time.shim.d.ts" />
import { ConfigType, Dayjs, PluginFunc, UnitType } from 'dayjs';

export const MS = 'millisecond';
export const S = 'second';
export const MIN = 'minute';
export const H = 'hour';
export const D = 'day';
export const W = 'week';
export const M = 'month';
export const Q = 'quarter';
export const Y = 'year';

export interface RelativeTimeThread {
  l: string;
  r?: number;
  d?: UnitType;
}

export interface RelativeTimeOptions {
  strict?: boolean;
  threads?: RelativeTimeThread[];
}

export const relativeTime: PluginFunc = (
  options: RelativeTimeOptions,
  c,
  d,
  // eslint-disable-next-line sonarjs/cognitive-complexity
) => {
  const proto = c.prototype;
  d.Ls.en.relativeTime = {
    future: 'in %s',
    past: '%s ago',
    s: 'a few seconds',
    m: 'a minute',
    mm: '%d minutes',
    h: 'an hour',
    hh: '%d hours',
    d: 'a day',
    dd: '%d days',
    M: 'a month',
    MM: '%d months',
    y: 'a year',
    yy: '%d years',
  };

  if (options?.strict) {
    Object.assign(d.Ls.en.relativeTime, {
      s: '%d second',
      ss: '%d seconds',
      m: '1 minute',
      h: '1 hour',
      d: '1 day',
      M: '1 month',
      y: '1 year',
    });
  }

  const fromTo = (
    input: ConfigType,
    withoutSuffix: boolean,
    instance: Dayjs,
    isFrom = false,
  ) => {
    // @ts-ignore
    const loc = instance.$locale().relativeTime;
    const T: RelativeTimeThread[] =
      options?.threads || options?.strict
        ? [
            { l: 's', r: 1 },
            { l: 'ss', r: 59, d: S },
            { l: 'm', r: 1 },
            { l: 'mm', r: 59, d: MIN },
            { l: 'h', r: 1 },
            { l: 'hh', r: 23, d: H },
            { l: 'd', r: 1 },
            { l: 'dd', r: 30, d: D },
            { l: 'M', r: 1 },
            { l: 'MM', r: 11, d: M },
            { l: 'y' },
            { l: 'yy', d: Y },
          ]
        : [
            { l: 's', r: 44, d: S },
            { l: 'm', r: 89 },
            { l: 'mm', r: 44, d: MIN },
            { l: 'h', r: 89 },
            { l: 'hh', r: 21, d: H },
            { l: 'd', r: 35 },
            { l: 'dd', r: 25, d: D },
            { l: 'M', r: 45 },
            { l: 'MM', r: 10, d: M },
            { l: 'y', r: 17 },
            { l: 'yy', d: Y },
          ];

    if (!loc.ss) {
      loc.ss = loc.s;
    }

    const Tl = T.length;
    let result;
    let out;
    let isFuture;

    for (let i = 0; i < Tl; i += 1) {
      let t = T[i];
      if (t.d) {
        result = isFrom
          ? d(input).diff(instance, t.d, true)
          : instance.diff(input, t.d, true);
      }
      const abs = Math[options?.strict ? 'floor' : 'round'](Math.abs(result));
      isFuture = result > 0;
      if (abs <= t.r || !t.r) {
        if (abs <= 1 && i > 0) t = T[i - 1]; // 1 minutes -> a minute
        const format = loc[t.l];
        if (typeof format === 'string') {
          out = format.replace('%d', String(abs));
        } else {
          out = format(abs, withoutSuffix, t.l, isFuture);
        }
        break;
      }
    }
    if (withoutSuffix) return out;
    return (isFuture ? loc.future : loc.past).replace('%s', out);
  };
  proto.to = function(input, withoutSuffix) {
    return fromTo(input, withoutSuffix, this, true);
  };
  proto.from = function(input, withoutSuffix) {
    return fromTo(input, withoutSuffix, this);
  };

  // @ts-ignore
  const makeNow = (thisDay: Dayjs) => ('$u' in thisDay ? d.utc() : d());

  proto.toNow = function(withoutSuffix) {
    return this.to(makeNow(this), withoutSuffix);
  };
  proto.fromNow = function(withoutSuffix) {
    return this.from(makeNow(this), withoutSuffix);
  };
};

I can raise a PR if you’d like to have this feature.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Time from now
Range Key Sample Output 0 to 44 seconds s a few seconds ago 45 to 89 seconds m a minute ago 90 seconds to 44 minutes...
Read more >
Javascript timestamp to relative time - datetime - Stack Overflow
I'm looking for a nice JS snippet to convert a timestamp (e.g. from Twitter API) to a nice user friendly relative time (e.g....
Read more >
npm install moment-precise-range-plugin - momentjs.com
The Precise Range plugin, written by Rob Dawson, can be used to display exact, ... 16:05:06"); // 1 year 2 months 3 days...
Read more >
Enabling Absolute Date/Time for JIRA issue view | Jira Cloud
JRACLOUD-36246 - User-friendly Relative Time Configuration & Date Time ... by seconds in our filters and so order is more important to us...
Read more >
New Plugin: Relative Time with Moment.js - Bubble Forum
Hi All, I have just published my first plugin. ... a text which shows days, hours, and seconds, till arrival of something, in...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found