• Stars
    star
    2,799
  • Rank 16,272 (Top 0.4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 10 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Web component extensions to the standard <time> element.

<relative-time> element

Formats a timestamp as a localized string or as relative text that auto-updates in the user's browser.

This allows the server to cache HTML fragments containing dates and lets the browser choose how to localize the displayed time according to the user's preferences. For example, the server may have cached the following generated markup:

<relative-time datetime="2014-04-01T16:30:00-08:00">
  April 1, 2014 4:30pm
</relative-time>

Every visitor is served the same markup from the server's cache. When it reaches the browser, the custom relative-time JavaScript localizes the element's text into the local timezone and formatting.

<relative-time datetime="2014-04-01T16:30:00-08:00">
  1 Apr 2014 21:30
</relative-time>

Dates are displayed before months, and a 24-hour clock is used, according to the user's browser settings.

If the browser's JavaScript is disabled, the default text served in the cached markup is still displayed.

Installation

Available on npm as @github/relative-time-element.

$ npm install @github/relative-time-element

This element uses the Intl.DateTimeFormat & Intl.RelativeTimeFormat APIs, which are supported by all modern JS engines. If you need to support an older browser, you may need to introduce a polyfill for Intl.DateTimeFormat & Intl.RelativeTimeFormat.

Usage

Add a <relative-time> element to your markup. Provide a default formatted date as the element's text content (e.g. April 1, 2014). It also MUST have a datetime attribute set to an ISO 8601 formatted timestamp.

<relative-time datetime="2014-04-01T16:30:00-08:00">
  April 1, 2014
</relative-time>

Depending on how far in the future this is being viewed, the element's text will be replaced with one of the following formats:

  • 6 years from now
  • 20 days from now
  • 4 hours from now
  • 7 minutes from now
  • just now
  • 30 seconds ago
  • a minute ago
  • 30 minutes ago
  • an hour ago
  • 20 hours ago
  • a day ago
  • 20 days ago
  • on Apr 1, 2014

So, a relative date phrase is used for up to a month and then the actual date is shown.

Attributes

Property Name Attribute Name Possible Values Default Value
datetime datetime string -
format format 'datetime'|'relative'|'duration' 'auto'
date - Date | null -
tense tense 'auto'|'past'|'future' 'auto'
precision precision 'year'|'month'|'day'|'hour'|'minute'|'second' 'second'
threshold threshold string 'P30D'
prefix prefix string 'on'
formatStyle format-style 'long'|'short'|'narrow' *
second second 'numeric'|'2-digit'|undefined undefined
minute minute 'numeric'|'2-digit'|undefined undefined
hour hour 'numeric'|'2-digit'|undefined undefined
weekday weekday 'short'|'long'|'narrow'|undefined **
day day 'numeric'|'2-digit'|undefined 'numeric'
month month 'numeric'|'2-digit'|'short'|'long'|'narrow'|undefined ***
year year 'numeric'|'2-digit'|undefined ****
timeZoneName time-zone-name 'long'|'short'|'shortOffset'|'longOffset' |'shortGeneric'|'longGeneric'|undefined undefined

*: If unspecified, formatStyle will return 'narrow' if format is 'elapsed' or 'micro', 'short' if the format is 'relative' or 'datetime', otherwise it will be 'long'.

**: If unspecified, month will return the same value as formatStyle whenever format is 'datetime', otherwise it will be 'short'.

***: If unspecified, weekday will return the same value as formatStyle whenever format is 'datetime', otherwise it will be undefined.

****: If unspecified, year will return 'numeric' if datetime represents the same year as the current year. It will return undefined if unspecified and if datetime represents a different year to the current year.

datetime (string)

This is the datetime that the element is meant to represent. This must be a valid ISO8601 DateTime. It is also possible to use the date property on the element to set the date. el.date expects a Date object, while el.datetime expects a string. Setting one will override the other.

<relative-time datetime="2014-04-01T16:30:00-08:00" tense="past">
  April 1, 2038 <!-- Will display "now" until April 1 2038 at 16:30:01! -->
</relative-time>
<script>
  const el = document.querySelector('relative-time')
  console.assert(el.date.toISOString() === el.datetime)
  el.date = new Date()
  console.assert(el.datetime !== "2014-04-01T16:30:00-08:00")
</script>
format ('datetime'|'relative'|'duration'|'auto'|'micro'|'elapsed')

Format can be either 'datetime', 'relative', or 'duration'. It can also be one of several deprecated formats of 'auto', 'micro', or 'elapsed'.

The default format is auto, which is an alias for relative. In the next major version this will be relative.

format=datetime

The datetime format will display a localised datetime, based on the other properties of the element. It uses Intl.DateTimeFormat to display the datetime in a localised format.

Unless specified, it will consider weekday to be 'long', month to be 'long', and 'year' to be numeric if the datetime is the same as the given year. Overriding formatStyle will change both weekday and month default values. Examples of this format with the default options and an en locale:

  • Wed, 26 Aug 2021
  • Sat, 31 Dec (assuming the datetime is same year as the current year)
format=relative

The default relative format will display dates relative to the current time (unless they are past the threshold value - see below). The values are rounded to display a single unit, for example if the time between the given datetime and the current wall clock time exceeds a day, then the format will only output in days, and will not display hours, minutes or seconds. Some examples of this format with the default options and an en locale:

  • in 20 days
  • 20 days ago
  • in 1 minute
  • on 31 Aug (assuming the current date is the same year as the current year, and is more than 30 days away from 31 Aug)
  • on 26 Aug 2021 (assuming the current date is more than 30 days away from 26 Aug 2021)
format=duration

The duration format will display the time remaining (or elapsed time) from the given datetime, counting down the number of years, months, weeks, days, hours, minutes, and seconds. Any value that is 0 will be omitted from the display by default. Examples of this format with the default options and an en locale:

  • 4 hours, 2 minutes, 30 seconds
  • 4 hours
  • 8 days, 30 minutes, 1 second
Deprecated Formats
format=elapsed

This is similar to the format=duration, except the formatStyle defaults to narrow. Code that uses format=elapsed should migrate to format=duration formatStyle=narrow, as it will be removed in a later version.

format=auto

This is identical to format=relative. Code that uses format=auto should migrate to format=relative as this will be the new default in a later version.

format=micro

The micro format which will display relative dates (within the threshold) in a more compact format. Similar to relative, the micro format rounds values to the nearest largest value. Additionally, micro format will not round lower than 1 minute, as such a datetime which is less than a minute from the current wall clock time will display '1m'.

Code that uses format=micro should consider migrating to format=relative (perhaps with formatStyle=narrow), as format=micro can be difficult for users to understand, and can cause issues with assistive technologies. For example some screen readers (such as VoiceOver for mac) will read out 1m as 1 meter.

Cheatsheet
format=datetime format=relative format=duration format=micro format=elapsed
Wed 26 May 2024 in 2 years 2 years, 10 days, 3 hours, 20 minutes, 8 seconds 2y 2y 10d 3h 20m 8s
Wed 26 Aug 2021 2 years ago 2 years, 10 days, 3 hours, 8 seconds 2y 2y 10d 3h 8s
Jan 15 2023 in 30 days 30 days, 4 hours, 20 minutes, 8 seconds 30d 30d 4h 20m 8s
Dec 15 2022 21 minutes ago 21 minutes, 30 seconds 21m 21m 30s
Dec 15 2022 37 seconds ago 37 seconds 1m 37s
tense ('auto'|'past'|'future', default: auto)

If format is 'datetime' then this value will be ignored.

Tense can be used to prevent duration or relative formatted dates displaying dates in a tense other than the one specified. Setting tense=past will always display future relative dates as now and duration dates as 0 seconds, while setting it to future will always display past dates relative as now and past duration dates as 0 seconds.

For example when the given datetime is 40 seconds behind of the current date:

tense= format=duration format=relative
future 0s now
past 40s 40s ago
auto 40s 40s ago
<relative-time datetime="2038-04-01T16:30:00-08:00" tense="past">
  April 1, 2038 <!-- Will display "now" until April 1 2038 at 16:30:01! -->
</relative-time>
<relative-time datetime="1970-04-01T16:30:00-08:00" tense="future">
  April 1, 2038 <!-- Will display "now" unless you had a time machine and went back to 1970 -->
</relative-time>

precision ('year'|'month'|'day'|'hour'|'minute'|'second', default: 'second')

If format is datetime then this value will be ignored.

Precision can be used to limit the display of an relative or duration formatted time. By default times will display down to the second level of precision. Changing this value will truncate the display by zeroing out any unit lower than the given unit, as such units smaller than the given unit won't be displayed during duration, and relative will display now if the time away from the current time is less than the given precision unit.

precision= format=duration
seconds 2y 6m 10d 3h 20m 8s
minutes 2y 6m 10d 3h 20m
hours 2y 6m 10d 3h
days 2y 6m 10d
months 2y 6m
years 2y
precision= format=relative
seconds 25 seconds
minutes now
hours now
days now
months now
years now
threshold (string, default: P30D)

If tense is anything other than 'auto', or format is 'relative' (or the deprecated 'auto' or 'micro' values), then this value will be ignored.

Threshold can be used to specify when a relative display (e.g. "5 days ago") should turn into an absolute display (i.e. the full date). This should be a valid ISO8601 Time Duration. If the difference between the current time and the specified datetime is more than the duration, then the date will be displayed as an absolute value (i.e. the full date), otherwise it will be formatted to a relative display (e.g. "5 days ago").

The default value for this is P30D, meaning if the current time is more than 30 days away from the specified date time, then an absolute date will be displayed.

<relative-time datetime="1970-04-01T16:30:00-08:00" threshold="P100Y">
  <!-- Will display "<N> years ago" until 2070 when it will display "on April 1, 1970" -->
</relative-time>
<relative-time datetime="1970-04-01T16:30:00-08:00" threshold="P0S">
  <!-- Will always display "on April 1, 1970" -->
</relative-time>
prefix (string, default: 'on')

If tense is anything other than 'auto', or format is anything other than 'relative' (or the deprecated 'auto' or 'micro' values), then this value will be ignored.

When formatting an absolute date (see above threshold for more details) it can be useful to prefix the date with some text. The default value for this is on but it can be any string value, an will be prepended to the date.

<relative-time datetime="1970-04-01T16:30:00-08:00" prefix="this happened on">
  <!-- Will always display "this happened on April 1, 1970" -->
</relative-time>
formatStyle ('long'|'short'|'narrow', default: 'narrow'|'long')

This will used to determine the length of the unit names. This value is passed to the Intl objects as the style option. Some examples of how this can be used:

format= formatStyle= Display
relative long in 1 month
relative short in 1 mo.
relative narrow in 1 mo.
duration long 1 month, 2 days, 4 hours
duration short 1 mth, 2 days, 4 hr
duration narrow 1m 2d 4h
second, minute, hour, weekday, day, month, year, timeZoneName

For dates outside of the specified threshold, the formatting of the date can be configured using these attributes. The values for these attributes are passed to Intl.DateTimeFormat:

lang

Lang is a built-in global attribute. Relative Time will use this to provide an applicable language to the Intl APIs. If the individual element does not have a lang attribute then it will traverse upwards in the tree to find the closest element that does, or default the lang to en.

Browser Support

Browsers without native custom element support require a polyfill.

Browsers without native support for Intl.RelativeTimeFormat or Intl.DateTimeFormat (such as Safari 13 or Edge 18) will also need polyfills.

  • Chrome
  • Firefox
  • Safari (version 14 and above)
  • Microsoft Edge (version 79 and above)

See Also

Most of this implementation is based on Basecamp's local_time component. Thanks to @javan for open sourcing that work and allowing for others to build on top of it.

@rmm5t's jquery-timeago is one of the old time-ago-in-words JS plugins.

More Repositories

1

gitignore

A collection of useful .gitignore templates
160,684
star
2

copilot-docs

Documentation for GitHub Copilot
23,229
star
3

docs

The open-source repo for docs.github.com
JavaScript
14,053
star
4

opensource.guide

πŸ“š Community guides for open source creators
HTML
12,947
star
5

gh-ost

GitHub's Online Schema-migration Tool for MySQL
Go
11,302
star
6

linguist

Language Savant. If your repository's language is being reported incorrectly, send us a pull request!
Ruby
10,684
star
7

semantic

Parsing, analyzing, and comparing source code across many languages
Haskell
8,865
star
8

copilot.vim

Neovim plugin for GitHub Copilot
Vim Script
8,286
star
9

codeql

CodeQL: the libraries and queries that power security researchers around the world, as well as code scanning in GitHub Advanced Security
CodeQL
7,579
star
10

roadmap

GitHub public roadmap
7,393
star
11

scientist

πŸ”¬ A Ruby library for carefully refactoring critical paths.
Ruby
7,389
star
12

personal-website

Code that'll help you kickstart a personal website that showcases your work as a software developer.
HTML
7,243
star
13

markup

Determines which markup library to use to render a content file (e.g. README) on GitHub
Ruby
5,678
star
14

dmca

Repository with text of DMCA takedown notices as received. GitHub does not endorse or adopt any assertion contained in the following notices. Users identified in the notices are presumed innocent until proven guilty. Additional information about our DMCA policy can be found at
DIGITAL Command Language
5,457
star
15

swift-style-guide

**Archived** Style guide & coding conventions for Swift projects
4,770
star
16

gemoji

Emoji images and names.
Ruby
4,280
star
17

training-kit

Open source courseware for Git and GitHub
HTML
4,247
star
18

explore

Community-curated topic and collection pages on GitHub
Ruby
3,840
star
19

mona-sans

Mona Sans, a variable font from GitHub
3,680
star
20

hubot-scripts

DEPRECATED, see https://github.com/github/hubot-scripts/issues/1113 for details - optional scripts for hubot, opt in via hubot-scripts.json
CoffeeScript
3,538
star
21

choosealicense.com

A site to provide non-judgmental guidance on choosing a license for your open source project
Ruby
3,379
star
22

git-sizer

Compute various size metrics for a Git repository, flagging those that might cause problems
Go
3,160
star
23

secure_headers

Manages application of security headers with many safe defaults
Ruby
3,104
star
24

gov-takedowns

Text of government takedown notices as received. GitHub does not endorse or adopt any assertion contained in the following notices.
3,088
star
25

archive-program

The GitHub Archive Program & Arctic Code Vault
3,000
star
26

scripts-to-rule-them-all

Set of boilerplate scripts describing the normalized script pattern that GitHub uses in its projects.
Shell
2,859
star
27

hotkey

Trigger an action on an element with a keyboard shortcut.
JavaScript
2,851
star
28

janky

Continuous integration server built on top of Jenkins and Hubot
Ruby
2,759
star
29

github-elements

GitHub's Web Component collection.
JavaScript
2,523
star
30

renaming

Guidance for changing the default branch name for GitHub repositories
2,408
star
31

view_component

A framework for building reusable, testable & encapsulated view components in Ruby on Rails.
Ruby
2,370
star
32

VisualStudio

GitHub Extension for Visual Studio
C#
2,365
star
33

glb-director

GitHub Load Balancer Director and supporting tooling.
C
2,255
star
34

SoftU2F

Software U2F authenticator for macOS
Swift
2,201
star
35

accessibilityjs

Client side accessibility error scanner.
JavaScript
2,180
star
36

CodeSearchNet

Datasets, tools, and benchmarks for representation learning of code.
Jupyter Notebook
2,155
star
37

balanced-employee-ip-agreement

GitHub's employee intellectual property agreement, open sourced and reusable
2,126
star
38

github-services

Legacy GitHub Services Integration
Ruby
1,902
star
39

platform-samples

A public place for all platform sample projects.
Shell
1,885
star
40

hubot-sans

Hubot Sans, a variable font from GitHub
Shell
1,832
star
41

pages-gem

A simple Ruby Gem to bootstrap dependencies for setting up and maintaining a local Jekyll environment in sync with GitHub Pages
Ruby
1,782
star
42

india

GitHub resources and information for the developer community in India
Ruby
1,769
star
43

haikus-for-codespaces

EJS
1,753
star
44

site-policy

Collaborative development on GitHub's site policies, procedures, and guidelines
1,743
star
45

government.github.com

Gather, curate, and feature stories of public servants and civic hackers using GitHub as part of their open government innovations
HTML
1,727
star
46

advisory-database

Security vulnerability database inclusive of CVEs and GitHub originated security advisories from the world of open source software.
1,711
star
47

objective-c-style-guide

**Archived** Style guide & coding conventions for Objective-C projects
1,682
star
48

covid19-dashboard

A site that displays up to date COVID-19 stats, powered by fastpages.
Jupyter Notebook
1,644
star
49

lightcrawler

Crawl a website and run it through Google lighthouse
JavaScript
1,471
star
50

rest-api-description

An OpenAPI description for GitHub's REST API
1,372
star
51

feedback

Public feedback discussions for: GitHub for Mobile, GitHub Discussions, GitHub Codespaces, GitHub Sponsors, GitHub Issues and more!
1,359
star
52

developer.github.com

GitHub Developer site
Ruby
1,314
star
53

backup-utils

GitHub Enterprise Backup Utilities
1,190
star
54

brubeck

A Statsd-compatible metrics aggregator
C
1,185
star
55

dev

Press the . key on any repo
1,184
star
56

catalyst

Catalyst is a set of patterns and techniques for developing components within a complex application.
TypeScript
1,183
star
57

codeql-action

Actions for running CodeQL analysis
TypeScript
1,152
star
58

securitylab

Resources related to GitHub Security Lab
C
1,150
star
59

opensourcefriday

🚲 Contribute to the open source community every Friday
HTML
1,143
star
60

graphql-client

A Ruby library for declaring, composing and executing GraphQL queries
Ruby
1,139
star
61

Rebel

Cocoa framework for improving AppKit
Objective-C
1,127
star
62

gh-actions-importer

GitHub Actions Importer helps you plan and automate the migration of Azure DevOps, Bamboo, Bitbucket, CircleCI, GitLab, Jenkins, and Travis CI pipelines to GitHub Actions.
C#
982
star
63

licensed

A Ruby gem to cache and verify the licenses of dependencies
Ruby
942
star
64

.github

Community health files for the @GitHub organization
869
star
65

swordfish

EXPERIMENTAL password management app. Don't use this.
Ruby
740
star
66

details-dialog-element

A modal dialog that's opened with <details>.
JavaScript
739
star
67

stack-graphs

Rust implementation of stack graphs
Rust
725
star
68

codeql-cli-binaries

Binaries for the CodeQL CLI
725
star
69

github-ds

A collection of Ruby libraries for working with SQL on top of ActiveRecord's connection
Ruby
667
star
70

email_reply_parser

Small library to parse plain text email content
Ruby
658
star
71

vulcanizer

GitHub's ops focused Elasticsearch library
Go
657
star
72

github-ospo

Helping open source program offices get started
641
star
73

webauthn-json

πŸ” A small WebAuthn API wrapper that translates to/from pure JSON using base64url.
TypeScript
638
star
74

gh-copilot

Ask for assistance right in your terminal.
637
star
75

rubocop-github

Code style checking for GitHub's Ruby projects
Ruby
616
star
76

safe-settings

JavaScript
606
star
77

codespaces-jupyter

Explore machine learning and data science with Codespaces
Jupyter Notebook
591
star
78

dat-science

Replaced by https://github.com/github/scientist
Ruby
582
star
79

maven-plugins

Official GitHub Maven Plugins
Java
581
star
80

details-menu-element

A menu opened with <details>.
JavaScript
554
star
81

trilogy

Trilogy is a client library for MySQL-compatible database servers, designed for performance, flexibility, and ease of embedding.
C
543
star
82

freno

freno: cooperative, highly available throttler service
Go
534
star
83

smimesign

An S/MIME signing utility for use with Git
Go
519
star
84

brasil

Recursos e informaçáes do GitHub para a comunidade de desenvolvedores no Brasil.
Ruby
515
star
85

gh-valet

Valet helps facilitate the migration of Azure DevOps, CircleCI, GitLab CI, Jenkins, and Travis CI pipelines to GitHub Actions.
C#
511
star
86

include-fragment-element

A client-side includes tag.
JavaScript
508
star
87

covid-19-repo-data

Data archive of identifiable COVID-19 related public projects on GitHub
505
star
88

vscode-github-actions

GitHub Actions extension for VS Code
TypeScript
492
star
89

vscode-codeql-starter

Starter workspace to use with the CodeQL extension for Visual Studio Code.
CodeQL
477
star
90

how-engineering-communicates

A community version of the "common API" for how the GitHub Engineering organization communicates
474
star
91

Archimedes

Geometry functions for Cocoa and Cocoa Touch
Objective-C
466
star
92

codeql-go

The CodeQL extractor and libraries for Go.
465
star
93

open-source-survey

The Open Source Survey
431
star
94

synsanity

netfilter (iptables) target for high performance lockless SYN cookies for SYN flood mitigation
C
424
star
95

entitlements-app

The Ruby Gem that Powers Entitlements - GitHub's Identity and Access Management System
Ruby
409
star
96

MVG

MVG = Minimum Viable Governance
379
star
97

issue-metrics

Gather metrics on issues/prs/discussions such as time to first response, count of issues opened, closed, etc.
Python
378
star
98

roskomnadzor

deprecated archive β€” moved to https://github.com/github/gov-takedowns/tree/master/Russia
376
star
99

clipboard-copy-element

Copy element text content or input values to the clipboard.
JavaScript
374
star
100

codespaces-react

JavaScript
364
star