SBB
SBB

Reputation: 8970

Javascript convert date to different format

I have a date picker which is in the format of 31-Dec-2014 as this is the format everyone is familiar with on our tool.

I am trying to convert it to a JavaScript date object in the format of mm/dd/yyyy but I am having a little trouble.

I tried something simple like var startDate = new Date('31-Dec-2014'); but it outputs invalid date.

I know there are plugins out there like date.js and moment.js but I feel like this would be simple to do without it.

Any ideas?

Upvotes: 0

Views: 146

Answers (1)

Paul S.
Paul S.

Reputation: 66304

Use the 3 param version of Date and translate your month code to the correct number, e.g.

function myDate(input) {
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
    input = input.split('-');
    input[1] = months.indexOf(input[1]);
    return new Date(+input[2], +input[1], +input[0]);
}

myDate('31-Dec-2014'); // Wed Dec 31 2014 00:00:00 GMT+0000 (GMT Standard Time)

Please remember all dates are generated in the client's local timezone, you may want to use the UTC methods instead.

Upvotes: 1

Related Questions