Everything You Need to Know About React Moments
Installation-
Node 6.4.0 or greater is required. Use npm install react-moment along with its peer dependency, moment. npm install –save moment react-moment
Timezone Support-
The moment- timezone package is required to use the timezone related functions.
npm install –save moment-timezone
The next step would be to import the package into your project.
import React from ‘react’;
import Moment from ‘react-moment’;
import ‘moment-timezone’;
export default class App extends React.Component {
…
}
Quick Start-
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
const dateToFormat = ‘1976-04-19T12:59-0500’;
<Moment>{dateToFormat}</Moment>
);
}
}
Outputs:
<time>Mon Apr 19 1976 12:59:00 GMT-0500</time>
The example given above could also be written in another way if you prefer to pass the date using an attribute rather than as a child to <Moment>.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
const dateToFormat = ‘1976-04-19T12:59-0500’;
<Moment date={dateToFormat} />
);
}
}
The date value that we mention can be a string, object, array or date instance:
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
const dateToFormat = new Date(‘1976-04-19T12:59-0500’);
<Moment date={dateToFormat} />
);
}
}
Props-
The following props are supported by this component:
1) Interval
Interval={number}
By default, the time updates every 60 seconds (60000 milliseconds). You can use the interval prop to change or disable updating.
This updates the time every 30 seconds.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment interval={30000}>
1976–04–19T12:59–0500
</Moment>
);
}
}
This process disables updating.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment interval={0}>
1976–04–19T12:59–0500
</Moment>
);
}
}
2) Formatting
Format={string}
This helps format the date according to the given format string.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment format=“YYYY/MM/DD”>
1976–04–19T12:59–0500
</Moment>
);
}
}
Outputs:
<time>1976/04/19</time>
3) Parsing Dates
Parse={string}
Moment can parse the most standard date formats. Use the parse attribute to tell moment how to parse the given date when non-standard.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment parse=“YYYY-MM-DD HH:mm”>
1976–04–19 12:59
</Moment>
);
}
}
4) Add and Subtract
Add={object}
Subtract={object}
Used to add and subtract periods of time from the given date, with the time periods expressed in the form of object literals.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
const date = new Date();
return (
<div>
<Moment add={{ hours: 12 }}>{date}</Moment>
<Moment add={{ days: 1, hours: 12 }}>{date}</Moment>
<Moment subtract={{ hours: 12 }}>{date}</Moment>
<Moment subtract={{ days: 1, hours: 12 }}>{date}</Moment>
</div>
);
}
}
5) From Now-
fromNow={bool}
This is also sometimes referred to as time ago or relative time and displays the date as the time from now, eg, “5 minutes ago”.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment fromNow>1976–04–19T12:59–0500</Moment>
);
}
}
Outputs:
<time>40 years ago</time>
When we include ago with fromNow, it will omit the suffic from the relative time.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment fromNow ago>1976–04–19T12:59–0500</Moment>
);
}
}
Outputs:
<time>40 years</time>
6) From Now During
fromNowDuring={number}
The setting fromNowDuring will help display the relative time like the fromNow but just during its value in milliseconds, after that format will be used instead.
7) From
From={string}
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment from=“2015-04-19”>1976–04–19T12:59–0500</Moment>
);
}
}
Outputs:
<time>39 years</time>
8) To Now
toNow={bool}
This is very similar to fromNow but gives the opposite interval.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment toNow>1976–04–19T12:59–0500</Moment>
);
}
}
Outputs:
<time>40 years ago</time>
9) To
To={string}
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment to=“2015-04-19”>1976–04–19T12:59–0500</Moment>
);
}
}
Outputs:
<time>39 years</time>
10) Filter
Filter={function}
A function that modifies/transforms the date value prior to rendering.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
const toUpperCaseFilter = (d) => {
return d.toUpperCase();
};
return (
const dateToFormat = ‘1976-04-19T12:59-0500’;
<Moment filter={toUpperCaseFilter}>{dateToFormat}</Moment>
);
}
}
Outputs:
<time>MON APR 19 1976 12:59:00 GMT-0500</time>
11) With Title
withTitle={bool}
It helps us by adding a title attribute to the element with the completion date.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment format=“D MMM YYYY” withTitle>
1976–04–19T12:59–0500
</Moment>
);
}
}
Outputs:
<time title=“1976-04-19T12:59-0500”>19 Apr 1976</time>
12) Title Format
titleFormat={string}
This shows us how the title date is formatted when using the withTitle attribute.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment titleFormat=“D MMM YYYY” withTitle>
1976–04–19T12:59–0500
</Moment>
);
}
}
Outputs:
<time title=“19 Apr 1976”>1976-04-19T12:59-0500</time>
13) Difference
diff={string}
decimal={bool}
unit={string}
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<div>
<Moment diff=“2015-04-19”>1976–04–19T12:59–0500</Moment>
<Moment diff=“2015-04-19” unit=“days”>1976–04–19T12:59–0500</Moment>
<Moment diff=“2015-04-19” unit=“years” decimal>1976–04–19T12:59–0500</Moment>
</div>
);
}
}
14) Duration
duration={string}
date={string}
This shows us the time elapsed between the two dates. The duration property should be behind the date property with respect to the time.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment duration=“2018-11-1T10:59-0500”
date=“2018-11-1T12:59-0500”
/>
);
}
}
15) Duration From Now
durationFromNow={bool}
This shows us the time completed between now and the provided datetime.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment date=“2018-11-1T12:59-0500”
durationFromNow
/>
);
}
}
16) Unix Timestamps
Unix={bool}
This tells a moment to parse the given date value as a Unix timestamp.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
const unixTimestamp = 198784740;
return (
<Moment unix>{unixTimestamp}</Moment>
);
}
}
Outputs:
<time>Mon Apr 19 1976 12:59:00 GMT-0500</time>
17) Local
Local={bool}
This gives the final output and results in the local time.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment local>
2018–11–01T12:59–0500
</Moment>
);
}
}
Outputs:
<time>Thu Nov 01 2018 18:59:00 GMT+0100</time>
18) Timezone
tz={string}
This sets the timezone and enables server side rendering. The client and server have to be provided with the same datetime, based on the common Timezones. The tz attribute will enable set the common timezone.
import React from ‘react’;
import Moment from ‘react-moment’;
import ‘moment-timezone’;
export default class MyComponent extends React.Component {
render() {
const unixTimestamp = 198784740;
return (
<Moment unix tz=“America/Los_Angeles”>
{unixTimestamp}
</Moment>
);
}
}
Outputs:
<time>Mon Apr 19 1976 09:59:00 GMT-0800</time>
19) Calendar
Calendar={object/bool}
This allows us to customize the strings used for the calendar function.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
const calendarStrings = {
lastDay : ‘[Yesterday at] LT’,
sameDay : ‘[Today at] LT’,
nextDay : ‘[Tomorrow at] LT’,
lastWeek : ‘[last] dddd [at] LT’,
nextWeek : ‘dddd [at] LT’,
sameElse : ‘L’
};
return (
<Moment calendar={calendarStrings}>
‘1976-04-19T12:59-0500’
</Moment>
);
}
}
20) Locale
Locale={string}
This sets the locale used to display the date.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
const dateToFormat = ‘1976-04-19T12:59-0500’;
return (
<Moment locale=“de”>{dateToFormat}</Moment>
);
}
}
21) Element
Element={string/React.Component}
Determines the element type to render as (string or function)
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment element=“span”>1976–04–19T12:59–0500</Moment>
);
}
}
Outputs:
<span>Mon Apr 19 1976 12:59:00 GMT-0500</span>
22) OnChange
onChange={func}
The onChange prop is called each time the date is updated, which by default is every 60 seconds. The function receives the new date value.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment onChange={(val) => { console.log(val); }}>
1976–04–19T12:59–0500
</Moment>
);
}
}
Other Props-
Any other properties are passed to the <time> element.
import React from ‘react’;
import Moment from ‘react-moment’;
export default class MyComponent extends React.Component {
render() {
return (
<Moment className=“datetime” aria-hidden={true}>
1976–04–19T12:59–0500
</Moment>
);
}
}
Output: <time class=“datetime” aria-hidden=“true”>Mon Apr 19 1976 12:59:00 GMT-0500</time>
Pooled Timer
By default, the timer is created for each mounted <Moment/> instance to update the date value. However, performance can take a hit. When you try to have many mounted instances. This problem is solved by using the pooled timer.
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import Moment from ‘react-moment’;
import App from ‘./components/app’;
// Start the pooled timer which runs every 60 seconds
// (60000 milliseconds) by default.
Moment.startPooledTimer();
// Or set the update interval. This will update the mounted
// instances every 30 seconds.
// Moment.startPooledTimer(30000);
ReactDOM.render(<App />, document.getElementById(‘mount’));
Global Config
Some prop values may be set globally so you don’t have to set them on every react-moment instance.
- globalMoment
- globalLocale
- globalFormat
- globalParse
- globalFilter
- globalElement
- globalTimezone
- globalLocal
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import moment from ‘moment/min/moment-with-locales’;
import Moment from ‘react-moment’;
// Sets the moment instance to use.
Moment.globalMoment = moment;
// Set the locale for every react-moment instance to French.
Moment.globalLocale = ‘fr’;
// Set the output format for every react-moment instance.
Moment.globalFormat = ‘D MMM YYYY’;
// Set the timezone for every instance.
Moment.globalTimezone = ‘America/Los_Angeles’;
// Set the output timezone for local for every instance.
Moment.globalLocal = true;
// Use a <span> tag for every react-moment instance.
Moment.globalElement = ‘span’;
// Upper case all rendered dates.
Moment.globalFilter = (d) => {
return d.toUpperCase();
};
const App = () => (
<Moment>1976–04–19T12:59–0500</Moment>
);
ReactDOM.render(<App />, document.getElementById(‘mount’));
You can override the global values on a per-instance basis using regular props.
import React from ‘react’;
import ReactDOM from ‘react-dom’;
import Moment from ‘react-moment’;
// Set the locale for every react-moment instance to French.
Moment.globalLocale = ‘fr’;
const App = () => (
<div>
{/*
Renders using the ‘fr’ locale due to the global setting.
*/}
<Moment>1976–04–19T12:59–0500</Moment>
{/*
Overrides the global locale and uses ‘en’ instead.
*/}
<Moment locale=“en”>1976–04–19T12:59–0500</Moment>
</div>
);
ReactDOM.render(<App />, document.getElementById(‘mount’));
Usage with React Native
If you are using React Native then you’ll have to pass in Text.
import Moment from ‘react-moment’;
import { Text } from ‘react-native’;
Then:
<Moment element={Text} >1976-04-19T12:59-0500</Moment>