Hi Friends đź‘‹,

Welcome To Infinitbility! ❤️

To format date in react js using moment, use the moment().format() method by passing desire format string parameters.

Just import moment in your file and invoke moment().format('DD-MM-YYYY hh:mm:ss'); it will show the current date time with the format.

moment().format('DD-MM-YYYY hh:mm:ss')

Today, I’m going to show How do I format date in react js using moment, here I will use the momentjs standard method format() to format the date object.

Let’s start today’s tutorial How do you format date in react js using moment?

Table of content

  1. Installation
  2. Moment Format rules
  3. Example in reactjs

Installation

Use the below installation command as per your package manager, moment support npm, Yarn, NuGet, spm, and meteor.

npm install moment --save   # npm
yarn add moment             # Yarn
Install-Package Moment.js   # NuGet
spm install moment --save   # spm
meteor add momentjs:moment  # meteor

Moment Format rules

Moment follow below rules to format date time as per user requirement like show am, pm in time string, show two digits year, and show date with st, nd, and rd.

Input Example Description
YYYY 2014 4 or 2 digit year. Note: Only 4 digit can be parsed on 'strict' mode
YY 14 2 digit year
Y -25 Year with any number of digits and sign
Q 1..4 Quarter of year. Sets month to first month in quarter.
M MM 1..12 Month number
MMM MMMM Jan..December Month name in locale set by moment.locale()
D DD 1..31 Day of month
Do 1st..31st Day of month with ordinal
DDD DDDD 1..365 Day of year
H HH 0..23 Hours (24 hour time)
h hh 1..12 Hours (12 hour time used with a A.)
k kk 1..24 Hours (24 hour time from 1 to 24)
a A am pm Post or ante meridiem (Note the one character a p are also considered valid)
m mm 0..59 Minutes
s ss 0..59 Seconds

After reading the above rules, you can easily understand how to format time as per your requirement. let’s see how we can use the format() method with the above rules.

Example in reactjs

In the following example, we are going to do

  1. import the moment package
  2. example of current date time format with am and pm DD-MM-YYYY h:mm:ss a
  3. example of custom date time format with am and pm DD-MM-YYYY h:mm:ss a

let’s write the code.

import moment from "moment";

function App() {
  return (
    <div>
        {/* example of current date time format with am and pm `DD-MM-YYYY h:mm:ss a` */}
        {console.log(moment().format("DD-MM-YYYY h:mm:ss a"))}
        {console.log("----")}
        {/* example of custom date time format with am and pm `DD-MM-YYYY h:mm:ss a` */}
        {console.log(moment('2016-10-08 10:29:23').format("DD-MM-YYYY h:mm:ss a"))}
    </div>
  );
}

export default App;

In the above program, we call moment().format() with format string rules.

let’s check the output.

MomentJs, Date format example in react js
MomentJs, Date format example in react js

I hope it’s help you, All the best 👍.