Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format custom time in moment.js?

Tags:

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".

like image 869
dev verma Avatar asked Nov 03 '16 05:11

dev verma


People also ask

How do you format time in a moment?

To get the current date and time, just call javascript moment() with no parameters like so: var now = moment(); This is essentially the same as calling moment(new Date()) . Unless you specify a time zone offset, parsing a string will create a date in the current time zone.

How do I change a moment date to a specific format?

Date Formatting Date format conversion with Moment is simple, as shown in the following example. moment(). format('YYYY-MM-DD'); Calling moment() gives us the current date and time, while format() converts it to the specified 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().

What is moment default format?

defaultFormat = "YYYY" 'YYYY' > moment().


2 Answers

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>
like image 194
Niyoko Avatar answered Sep 18 '22 09:09

Niyoko


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

like image 27
Junior Grão Avatar answered Sep 21 '22 09:09

Junior Grão