dev verma
dev verma

Reputation: 777

How to format custom time in moment.js?

I have tried moment.time(column.start_time).format("hh:mm A") but it give me error.

I have custom time field value is "15:30:00" want to format like "03:30 PM".

Upvotes: 40

Views: 82634

Answers (2)

Junior Grão
Junior Grão

Reputation: 1691

I will include one more additional information:

When you use hh:mm A

var time = "15:30:00";
var formatted = moment(time, "HH:mm").format("hh:mm A");
console.log(formatted); 
//it will return 03:30 PM

And when you use LT

var time = "15:30:00";
var formatted = moment(time, "HH:mm:ss").format("LT");
console.log(formatted); 
//it will return 3:30 PM

The difference between one and another is just a 0 before the first number when it is lower then 10. I am working with date time picker and then I understood why it was not binding in my combo box.

More details in: https://momentjscom.readthedocs.io/en/latest/moment/04-displaying/01-format/#localized-formats

I hope it can help

Upvotes: 16

Niyoko
Niyoko

Reputation: 7672

You need to add a format string into the moment function because your date is not a valid ISO date.

var time = "15:30:00";
var formatted = moment(time, "HH:mm:ss").format("hh:mm A");
console.log(formatted); 
<script src="https://momentjs.com/downloads/moment.min.js"></script>

Upvotes: 78

Related Questions