Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format hours, minutes and seconds with moment.js

Tags:

momentjs

I get this value from my backend service: 171054. It represents hh:mm:ss. But when I use the formatting options from the docs it gives me back 00:00:00.

Things I've tried:

moment('171054').format('hh-mm-ss')
moment('171054').format('HH-mm-ss')
moment('171054').format('HH-MM-SS')
like image 835
Jim Peeters Avatar asked Oct 26 '16 07:10

Jim Peeters


People also ask

How do I change moment format time?

Try: moment({ // Options here }). format('HHmm') . That should give you the time in a 24 hour format.

What is Moment () hour ()?

The moment(). hour() Method is used to get the hours from the current time or to set the hours. Syntax: moment().hour(); or. moment().


1 Answers

You are confusing format option with parsing option. Since your input string is not in ISO 8601 format, you have to specify format when parsing.

Here a working example for your use case:

var mom = moment('171054', 'HHmmss');
console.log(mom.format());
console.log(mom.format('HH:mm:ss'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
like image 82
VincenzoC Avatar answered Oct 13 '22 19:10

VincenzoC