Using moment.js to convert date to string “MM/dd/yyyy” Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Using moment.js to convert date to string “MM/dd/yyyy” without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I need to take the date value from jquery datepicker turn it into string format “MM/dd/yyyy” so it can do the right ajax post. When the page loads or upon changing the datepicker, a jquery ajax call is made.

I have this code:

var sTimestamp =
moment($("#start_ts").datepicker("getDate")).format("MM/dd/yyyy");

But it doesn’t turn it into “MM/dd/yyyy”. When I use fiddler to check what is sent down the wire, this is the body:

startTimestamp=03%2FTh%2Fyyyy&endTimestamp=03%2FTh%2Fyyyy&pageSize=50&pageNum=0

If I use the compose in fiddler and change the body to:

startTimestamp=03/13/2013&endTimestamp=03/14/2013&pageSize=50&pageNum=0

I get the right response. So, my question is, is there a way to take a date object and format it to a string “MM/dd/yyyy” using moment.js? Or is there something wrong with the way I get the date from datepicker?

Btw, I am assuming that datepicker.getDate returns a date object since that’s what the jQuery docs tell me.

Thank you,

Answer

I think you just have incorrect casing in the format string. According to the documentation this should work for you: MM/DD/YYYY

moment.js documentation

We are here to answer your question about Using moment.js to convert date to string “MM/dd/yyyy” - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji