javascriptdayjs

Customise format of dayjs relative time plugin


I'm using dayjs with the RelativeTime plugin.

To get a future date:

dayjs().to(dayjs("2030-01-01"));          // "in 5 years"
dayjs().to(dayjs("2030-01-01"), true);    // "5 years"

I want to customise the format, e.g. "5 years from now".

How do I do that? The docs and repo discussions hint that formats can be customised, but I can't find examples for this specific plugin.

Note I don't want a hack like dayjs().to(dayjs("2030-01-01"), true) + ' from now', as it would make the code more complicated (I'd need to evaluate whether it's in the past or future, etc.) I want to customise the format, if possible.


Solution

  • It can be customised like so:

    dayjs.extend(window.dayjs_plugin_relativeTime);
    dayjs.extend(window.dayjs_plugin_updateLocale);
    
    dayjs().to(dayjs("2030-01-01"));     // "in 5 years"
    
    dayjs.updateLocale('en', {
      relativeTime: {
        future: "%s from now",           // <---------- default is "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"
      }
    });
    
    dayjs().to(dayjs("2030-01-01"));   // "5 years from now"
    

    That requires the UpdateLocale plugin.

    To update the entire locale just to set one template is nasty, but there's an open issue and unmerged PR to fix that, someday.