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.
1moment().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
- Installation
- Moment Format rules
- Example in reactjs
Installation
Use the below installation command as per your package manager, moment support npm, Yarn, NuGet, spm, and meteor.
1npm install moment --save # npm2yarn add moment # Yarn3Install-Package Moment.js # NuGet4spm install moment --save # spm5meteor 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
- import the moment package
- example of 24-hour format time
HH:mm:ss
- example of 12-hour format time
h:mm:ss a
let’s write the code.
1import moment from "moment";23function App() {4 return (5 <div>6 {/* example of 24 hour format time `HH:mm:ss` */}7 {console.log(moment().format("HH:mm:ss"))}8 {console.log("----")}9 {/* example of 12 hour format time `h:mm:ss a` */}10 {console.log(moment().format("h:mm:ss a"))}11 </div>12 );13}1415export default App;
In the above program, we call moment().format()
with format string rules.
let’s check the output.

I hope it’s help you, All the best 👍.
Follow me on Twitter
Join our email list and get notified about new content
No worries, I respect your privacy and I will never abuse your email.
Every week, on Tuesday, you will receive a list of free tutorials I made during the week (I write one every day) and news on other training products I create.