Unbreakable Unbreakable - 3 months ago 18
Javascript Question

How to convert date time in format mm/dd/yyyy

My

VB.net
Rest service at backend expects date in below format:

starterInput.dateProp = 08/26/2016 where dateProp is of date type


Currently I am getting date in below format in my front end
Javascript


start = 2016-08-26T03:59:59.999Z


How can I convert my date of
2016-08-26T03:59:59.999Z
to
08/26/2016
in Javascript

I have tried some of the built in function.

start.toArray()
gives me something like
[2016, 7, 10, 3, 59, 59, 0]

So shall I parse this array and use the index to create something like
08/26/2016
and then send it to the backend. I tried some other functions too which are available in javascript, like:

start.format()

output: "2016-08-10T03:59:59+00:00"

start.toString()

output: ""Wed Aug 08 2016 03:59:59 GMT+0000"


I am confused how to get the date in the format I expect
08/26/2016
. Please guide me. Thanks!

Answer

If you're just trying to convert the JavaScript date object to a string like the following: 08/26/2016 then you can do as follows:

        function getFormattedDate(date) {
            var year = date.getFullYear();
            /// Add 1 because JavaScript months start at 0
            var month = (1 + date.getMonth()).toString();
            month = month.length > 1 ? month : '0' + month;
            var day = date.getDate().toString();
            day = day.length > 1 ? day : '0' + day;
            return month + '/' + day + '/' + year;
        }

        var formattedStart = getFormattedDate(start);