Hi Friends 👋,

Welcome To Infinitbility! ❤️

To format time in moment js, just use the moment().format() method by passing desire format string parameters.

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

moment().format('hh:mm:ss')

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

Let’s start the today’s tutorial How do you format time in moment js?

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 24-hour format time HH:mm:ss
  3. example of 12-hour format time h:mm:ss a

let’s write the code.

import moment from "moment";

function App() {
  return (
    <div>
        {/* example of 24 hour format time `HH:mm:ss` */}
        {console.log(moment().format("HH:mm:ss"))}
        {console.log("----")}
        {/* example of 12 hour format time `h:mm:ss a` */}
        {console.log(moment().format("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, Time Format example
MomentJs, Time Format example

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