How to use MomentJS library with React Native

By Rashid •  October 31st, 2019 • 

MomentJS is an extremely useful JavaScript library when you have some complex things to do with date and time. It parse, validate, manipulate, and display dates and times in JavaScript. Let’s check how to use momentJS library with react native.

Install Moment.js library in your react native project using any of the commands given below.
npm install moment –save
yarn add moment

After installing, import the library to your file as given below.

import moment from "moment";

You can display current date and time using moment as given below.


Here’s the react native code to display current date and time using momentjs.

import React, {Component} from 'react';
import {View, Text, StyleSheet} from 'react-native';
import moment from 'moment';
export default class App extends Component {
constructor(props) {
this.state = {};
render() {
return (
<View style={styles.container}>
<Text>Current Date: {moment().format()} </Text>
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
justifyContent: 'center',
alignItems: 'center',
view raw App.js hosted with ❤ by GitHub

Let’s explore more. Momentjs can be used to show dates in various formats.

moment().format('MMMM Do YYYY, h:mm:ss a'); // October 29th 2019, 12:14:46 pm
moment().format('dddd');                    // Tuesday
moment().format("MMM Do YY");               // Oct 29th 19
moment().format('DD-MM-YYYY');              // 29-10-2019

You can also convert one format of date into desired format using Momentjs.

moment("23MAY2099", 'DDMMMYYYY').format('YYYY-MM-DD'); //2099-05-23

Momentjs helps you to display relative time which can be used in applications which have chats and notifications.

moment("20111031", "YYYYMMDD").fromNow(); // 8 years ago
moment("20120620", "YYYYMMDD").fromNow(); // 7 years ago
moment().startOf('day').fromNow();        // 12 hours ago
moment().endOf('day').fromNow();          // in 12 hours

The calendar time can be retrieved using calendar method.

moment().subtract(10, 'days').calendar(); // 10/19/2019
moment().subtract(6, 'days').calendar();  // Last Wednesday at 12:28 PM
moment().subtract(3, 'days').calendar();  // Last Saturday at 12:28 PM
moment().subtract(1, 'days').calendar();  // Yesterday at 12:28 PM
moment().calendar();                      // Today at 12:28 PM
moment().add(1, 'days').calendar();       // Tomorrow at 12:28 PM
moment().add(3, 'days').calendar();       // Friday at 12:28 PM   

Please note that the outputs given above are not accurate as it shows the outputs at the time of the blog post creation.

The scope of using Momentjs with react native is not ending here, you can explore more on here.


Keep Reading