All Projects → catamphetamine → react-time-ago

catamphetamine / react-time-ago

Licence: MIT license
Localized relative date/time formatting in React

Programming Languages

javascript
184084 projects - #8 most used programming language
HTML
75241 projects
CSS
56736 projects

Labels

Projects that are alternatives of or similar to react-time-ago

jinja2-time
📆 Jinja2 Extension for Dates and Times
Stars: ✭ 64 (-27.27%)
Mutual labels:  time
HijriDatePicker
Material (Gregorian - Hijri) Date & Time Picker
Stars: ✭ 128 (+45.45%)
Mutual labels:  time
Shell-Scripts
Shell scripts about some basic topics, current time, calculator, sorting, restaurant and more.
Stars: ✭ 100 (+13.64%)
Mutual labels:  time
time-formater
在javascript中显示日期。
Stars: ✭ 44 (-50%)
Mutual labels:  time
timestampy
🕒 Bunch of utilities useful when working with UNIX timestamps
Stars: ✭ 21 (-76.14%)
Mutual labels:  time
simple-analog-clock
Simple clock view for displaying uh...time?
Stars: ✭ 24 (-72.73%)
Mutual labels:  time
about-time
A cool helper for tracking time and throughput of code blocks, with beautiful human friendly renditions.
Stars: ✭ 36 (-59.09%)
Mutual labels:  time
Language Time
A library that converts Time to its equivalent local languages starting with some basic Nigeria languages(Yoruba, Hausa, Igbo, Efik and English)
Stars: ✭ 51 (-42.05%)
Mutual labels:  time
ts-business-time
Business time / market hours logic for TypeScript
Stars: ✭ 18 (-79.55%)
Mutual labels:  time
akka-mock-scheduler
A mock Akka scheduler to simplify testing scheduler-dependent code
Stars: ✭ 86 (-2.27%)
Mutual labels:  time
chronos
One library to rule the time
Stars: ✭ 17 (-80.68%)
Mutual labels:  time
ESPNtpClient
High accuracy NTP library for ESP32 and ESP8266
Stars: ✭ 81 (-7.95%)
Mutual labels:  time
timezones
Nim timezone library compatible with the standard library.
Stars: ✭ 37 (-57.95%)
Mutual labels:  time
ios-application
A native, lightweight and secure one-time-password (OTP) client built for iOS; Raivo OTP!
Stars: ✭ 581 (+560.23%)
Mutual labels:  time
rescript-date
📆 Date manipulation in ReScript.
Stars: ✭ 101 (+14.77%)
Mutual labels:  time
popoPicker
popoPicker是一个移动端3D滚轮日期时间和单项的选择器,支持无限循环滚动,不依赖第三方库
Stars: ✭ 26 (-70.45%)
Mutual labels:  time
TimeMail
Write a letter to the future,After many years, I hope you will live up to your expectations.
Stars: ✭ 33 (-62.5%)
Mutual labels:  time
ad-alexatalkingclock
Alexa (or other Smart Speakers) tell you the time without asking every hour. Please ⭐️if you like my app :)
Stars: ✭ 30 (-65.91%)
Mutual labels:  time
timezz
With this plugin, you can easily make a stopwatch or timer on your site. Just init, style and enjoy.
Stars: ✭ 35 (-60.23%)
Mutual labels:  time
meta-theme-sky-color
Js snippet that changes the mobile Chrome nav bar color to the color of the sky based on time of day.
Stars: ✭ 19 (-78.41%)
Mutual labels:  time

react-time-ago

npm version

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

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 library for generating date/time labels, so both of these packages should be installed:

$ npm install react-time-ago javascript-time-ago --save

If you're not using a bundler then use a standalone version from a CDN.

Use

First, javascript-time-ago must be initialized with some locales:

./src/index.js

import TimeAgo from 'javascript-time-ago'

import en from 'javascript-time-ago/locale/en.json'
import ru from 'javascript-time-ago/locale/ru.json'

TimeAgo.addDefaultLocale(en)
TimeAgo.addLocale(ru)

Then, use <ReactTimeAgo/> component:

./src/LastSeen.js

import React from 'react'
import ReactTimeAgo from 'react-time-ago'

export default function LastSeen({ date }) {
  return (
    <div>
      Last seen: <ReactTimeAgo date={date} locale="en-US"/>
    </div>
  )
}

Style

<ReactTimeAgo/> component accepts an optional timeStyle property — it should be a javascript-time-ago style: either a built-in style name (like "round", "round-minute", "twitter", etc) or a custom style object.

<ReactTimeAgo date={date} locale="en-US" timeStyle="twitter"/>

React Native

By default, this component renders a <time/> HTML tag. When using this component in React Native, pass a custom component property:

import React from 'react'
import PropTypes from 'prop-types'
import ReactTimeAgo from 'react-time-ago'

export default function TimeAgo(props) {
  return <ReactTimeAgo {...props} component={Time}/>
}

function Time({ date, verboseDate, tooltip, children }) {
  return <Text>{children}</Text>
}

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, <ReactTimeAgo/> 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: <time>2 days ago</time>) 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:

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 (
    <ReactTimeAgo
      {...props}
      wrapperComponent={TooltipContainer}
      tooltip={false}/>
  )
}

const TooltipContainer = ({ verboseDate, children, ...rest }) => (
  <Tooltip {...rest} content={verboseDate}>
    {children}
  </Tooltip>
)

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.

<ReactTimeAgo future date={date} .../>

CDN

One can use any npm CDN service, e.g. unpkg.com or jsdelivr.com

<!-- Example `[version]`: `2.x` -->
<script src="https://unpkg.com/javascript-time-ago@[version]/bundle/javascript-time-ago.js"></script>
<script src="https://unpkg.com/react-time-ago@[version]/bundle/react-time-ago.js"></script>

<script>
  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"
        }
      },
      ...
    }
  })
</script>

<script>
  ...
  <ReactTimeAgo date={new Date()} locale="en-US" timeStyle="twitter"/>
  ...
</script>

Props

// The `date` (or `timestamp`).
// 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,

// 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 `<ReactTimeAgo/>` component.
// * children: string — The relative time label.
// * All "unknown" properties that have been passed to `<ReactTimeAgo/>` are passed through to this component.
component: PropTypes.elementType.isRequired,

// 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.isRequired,

// 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,

// 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,

// (advanced)
// A React Component to wrap the resulting `<time/>` 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.func,

// 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 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. 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

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].