github / relative-time-element

Web component extensions to the standard <time> element.

Home Page:https://github.github.io/relative-time-element/examples/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

relative-time - Hard-coded format for non-relative output

nomego opened this issue · comments

The element is pretty limited to English and the github date style right now.
There should be a way to supply a strftime format for anything that is too old to be displayed in relative terms.

For example:
https://github.com/github/time-elements/blob/77a086c07630ae2fefb1a763a2d5212b72de79d2/src/relative-time.js#L23

If anyone's interested, here's what I'm doing to work around it. This will show a locale-formatted date instead of an "on..." string. You need to use <gf-relative-time> for this, but change it however you like.

import {RelativeTimeElement} from '@github/time-elements';

class GFRelativeTimeElement extends RelativeTimeElement {
  getLang() {
    return document.documentElement.getAttribute("lang")
  }

  // Don't show "on... ", show a localized date.
  // https://github.com/github/time-elements/issues/120
  getFormattedDate() {
    let v = super.getFormattedDate();
    if (v.startsWith('on ')) {
      return (new Date(this.getAttribute("datetime"))).toLocaleDateString(this.getLang());
    }
    return v;
  }
}

if (!window.customElements.get('gf-relative-time')) {
  window.GFRelativeTimeElement = GFRelativeTimeElement;
  window.customElements.define('gf-relative-time', GFRelativeTimeElement);
}

In v3.2.0 you can customise the format in many ways; either use format= to apply a strftime compatible format, or use the options that align to the DateTimeFormat options. For more check out the new Readme,