https://github.com/catamphetamine/react-time-ago
Localized relative date/time formatting in React
https://github.com/catamphetamine/react-time-ago
react time
Last synced: about 1 month ago
JSON representation
Localized relative date/time formatting in React
- Host: GitHub
- URL: https://github.com/catamphetamine/react-time-ago
- Owner: catamphetamine
- License: mit
- Created: 2016-04-11T08:40:04.000Z (about 9 years ago)
- Default Branch: master
- Last Pushed: 2024-05-06T18:07:11.000Z (about 1 year ago)
- Last Synced: 2025-04-06T04:31:59.554Z (2 months ago)
- Topics: react, time
- Language: JavaScript
- Homepage: https://catamphetamine.github.io/react-time-ago/
- Size: 2.5 MB
- Stars: 100
- Watchers: 5
- Forks: 13
- Open Issues: 1
-
Metadata Files:
- Readme: README.md
- Changelog: CHANGELOG.md
- License: LICENSE
- Code of conduct: CODE_OF_CONDUCT.md
Awesome Lists containing this project
README
# react-time-ago
[](https://www.npmjs.com/package/react-time-ago)
Localized relative date/time formatting (both for past and future dates).
Automatically chooses the right units (seconds, minutes, etc) to format a time interval.
Automatically refreshes itself.
[See Demo](https://catamphetamine.gitlab.io/react-time-ago/)
Examples:
* just now
* 45s
* 5m
* 15 minutes ago
* 3 hours ago
* in 2 months
* in 5 years
* …## Install
The `react-time-ago` component uses [`javascript-time-ago`](https://gitlab.com/catamphetamine/javascript-time-ago) library for generating date/time labels, so both of these packages should be installed:
```sh
$ npm install react-time-ago javascript-time-ago --save
```If you're not using a bundler then use a [standalone version from a CDN](#cdn).
## Use
First, `javascript-time-ago` must be [initialized](https://github.com/catamphetamine/javascript-time-ago#locales) with some locales:
#### ./src/index.js
```js
import TimeAgo from 'javascript-time-ago'import en from 'javascript-time-ago/locale/en'
import ru from 'javascript-time-ago/locale/ru'TimeAgo.addDefaultLocale(en)
TimeAgo.addLocale(ru)
```Then, use `` component:
#### ./src/LastSeen.js
```js
import React from 'react'
import ReactTimeAgo from 'react-time-ago'export default function LastSeen({ date }) {
return (
Last seen:
)
}
```## Hook
If you prefer using a React Hook instead of a React Component, the parameters for it are the same as the [props](#props) for the React component, except:
* `tooltip: boolean`
* `component: React.Component`
* `wrapperComponent: React.Component`
* `wrapperProps: object````js
import { useTimeAgo } from 'react-time-ago'const result = useTimeAgo(parameters)
```Returns an object with properties:
* `date: Date` — Same as the `date` input parameter. If the input parameter was a timestamp (`number`) then it gets converted to a `Date`.
* `formattedDate: string` — Formatted `date`. Example: `"5 min ago"`.
* `verboseDate: string` — Formatted `date` (verbose variant). Example: `"Thursday, December 20, 2012, 7:00:00 AM GMT+4"`.## Style
`` component accepts an optional `timeStyle` property — it should be a `javascript-time-ago` [style](https://github.com/catamphetamine/javascript-time-ago#styles): either a built-in style name (like `"round"`, `"round-minute"`, `"twitter"`, etc) or a [custom](https://github.com/catamphetamine/javascript-time-ago#custom) style object.
```js
```
## React Native
By default, this component renders a `` HTML tag. When using this component in React Native, pass a custom `component` property:
```js
import React from 'react'
import PropTypes from 'prop-types'
import ReactTimeAgo from 'react-time-ago'export default function TimeAgo(props) {
return
}function Time({ date, verboseDate, tooltip, children }) {
return {children}
}Time.propTypes = {
date: PropTypes.instanceOf(Date).isRequired,
verboseDate: PropTypes.string,
tooltip: PropTypes.bool.isRequired,
children: PropTypes.string.isRequired
}
```## Tooltip
By default, the standard HTML `title` attribute is used to display a tooltip with the verbose date on mouse over.
For custom tooltip design, a custom tooltip component could be rendered. For that, `` supports properties:
* `tooltip={false}` — Instructs the component not to add the default HTML `title` attribute.
* `wrapperComponent` — A React component that's gonna wrap the date/time label. Receives properties: `children` (Example: ``) and `verboseDate: string` (Example: "Wednesday, January 1, 2000, 10:45:10 PM").
* `wrapperProps` — If defined, these properties are passed through to the `wrapperComponent`.For example, here's how to render a [`react-responsive-ui/Tooltip`](https://catamphetamine.gitlab.io/react-responsive-ui/#tooltip):
```js
import React from 'react'
import PropTypes from 'prop-types'
import Tooltip from 'react-responsive-ui/commonjs/Tooltip'
import ReactTimeAgo from 'react-time-ago'
import 'react-time-ago/Tooltip.css'export default function ReactTimeAgoWithTooltip(props) {
return (
)
}const TooltipContainer = ({ verboseDate, children, ...rest }) => (
{children}
)TooltipContainer.propTypes = {
// `verboseDate` is not generated on server side
// (because tooltips are only shown on mouse over),
// so it's not declared a "required" property.
verboseDate: PropTypes.string,
children: PropTypes.node.isRequired
}
```## Future
When given future dates, `.format()` produces the corresponding output.: `"in 5 minutes"`, `"in 10 days"`, etc.
To restrict the formatted date to be future-only, pass `future` property, and it will stop when it reaches "zero point" (`"in a moment"`) and won't allow the `date` to be formatted as a past one.
```js
```
## CDN
One can use any npm CDN service, e.g. [unpkg.com](https://unpkg.com) or [jsdelivr.com](https://jsdelivr.com)
```html
TimeAgo.addDefaultLocale({
locale: 'en',
now: {
now: {
current: "now",
future: "in a moment",
past: "just now"
}
},
long: {
year: {
past: {
one: "{0} year ago",
other: "{0} years ago"
},
future: {
one: "in {0} year",
other: "in {0} years"
}
},
...
}
})...
<ReactTimeAgo date={new Date()} locale="en-US" timeStyle="twitter"/>
...```
## Props
```js
// `date: Date` or `timestamp: number`.
// E.g. `new Date()` or `1355972400000`.
date: PropTypes.oneOfType([
PropTypes.instanceOf(Date),
PropTypes.number
]).isRequired,// Preferred locale.
// Is 'en' by default.
// E.g. 'ru-RU'.
locale: PropTypes.string,// Alternatively to `locale`, one could pass `locales`:
// A list of preferred locales (ordered).
// Will choose the first supported locale from the list.
// E.g. `['ru-RU', 'en-GB']`.
locales: PropTypes.arrayOf(PropTypes.string),// If set to `true`, then will stop at "zero point"
// when going from future dates to past dates.
// In other words, even if the `date` has passed,
// it will still render as if `date` is `now`.
future: PropTypes.bool,// Date/time formatting style.
// See `javascript-time-ago` docs on "Styles" for more info.
// E.g. 'round', 'round-minute', 'twitter', 'twitter-first-minute'.
timeStyle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object
]),// `round` parameter of `javascript-time-ago`.
// See `javascript-time-ago` docs on "Rounding" for more info.
// Examples: "round", "floor".
round: PropTypes.string,// If specified, the time won't "tick" past this threshold (in seconds).
// For example, if `minTimeLeft` is `60 * 60`
// then the time won't "tick" past "in 1 hour".
minTimeLeft: PropTypes.number,// A React component to render the relative time label.
// Receives properties:
// * date: Date — The date.
// * verboseDate: string — Formatted verbose date.
// * tooltip: boolean — The `tooltip` property of `` component.
// * children: string — The relative time label.
// * All "unknown" properties that have been passed to `` are passed through to this component.
component: PropTypes.elementType,// Whether to use HTML `tooltip` attribute to show a verbose date tooltip.
// Is `true` by default.
// Can be set to `false` to disable the native HTML `tooltip`.
tooltip: PropTypes.bool,// Verbose date formatter.
// By default it's `(date) => new Intl.DateTimeFormat(locale, {…}).format(date)`.
formatVerboseDate: PropTypes.func,// `Intl.DateTimeFormat` format for formatting verbose date.
// See `Intl.DateTimeFormat` docs for more info.
verboseDateFormat: PropTypes.object,// (deprecated)
// How often the component refreshes itself.
// When not provided, will use `getNextTimeToUpdate()` feature
// of `javascript-time-ago` styles to determine the update interval.
updateInterval: PropTypes.oneOfType([
PropTypes.number,
PropTypes.arrayOf(PropTypes.shape({
threshold: PropTypes.number,
interval: PropTypes.number.isRequired
}))
]),// (deprecated).
// Set to `false` to disable automatic refresh of the component.
// Is `true` by default.
// I guess no one actually turns auto-update off, so this parameter is deprecated.
tick: PropTypes.bool,// Allows setting a custom baseline for relative time measurement.
// https://gitlab.com/catamphetamine/react-time-ago/-/issues/4
now: PropTypes.number,// Allows offsetting the `date` by an arbitrary amount of milliseconds.
// https://gitlab.com/catamphetamine/react-time-ago/-/issues/4
timeOffset: PropTypes.number,// Pass `false` to use native `Intl.RelativeTimeFormat` / `Intl.PluralRules`
// instead of the polyfilled ones in `javascript-time-ago`.
polyfill: PropTypes.bool,// (advanced)
// A React Component to wrap the resulting `` React Element.
// Receives `verboseDate` and `children` properties.
// Also receives `wrapperProps`, if they're passed.
// `verboseDate` can be used for displaying verbose date label
// in an "on mouse over" (or "on touch") tooltip.
// See the "Tooltip" readme section for more info.
// Another example could be having `wrapperComponent`
// being rerendered every time the component refreshes itself.
wrapperComponent: PropTypes.elementType,// Custom `props` passed to `wrapperComponent`.
wrapperProps: PropTypes.object
```## TypeScript
This library comes with TypeScript "typings". If you happen to find any bugs in those, create an issue.
## GitHub
On March 9th, 2020, GitHub, Inc. silently [banned](https://medium.com/@catamphetamine/how-github-blocked-me-and-all-my-libraries-c32c61f061d3) my account (erasing all my repos, issues and comments) without any notice or explanation. Because of that, all source codes had to be promptly moved to [GitLab](https://gitlab.com/catamphetamine/react-time-ago). GitHub repo is now deprecated, and the latest source codes can be found on GitLab, which is also the place to report any issues.
## License
[MIT](LICENSE)