How can I convert this complicated date format to this in javascript

var d = new Date("Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)");
var str = $.datepicker.formatDate('yy-mm-dd', d);
alert(str);

http://jsfiddle.net/3tNN8/

This requires jQuery UI.


You can do it like this

var date = new Date("Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)");
var year=date.getFullYear();
var month=date.getMonth()+1 //getMonth is zero based;
var day=date.getDate();
var formatted=year+"-"+month+"-"+day;

I see you're trying to format a date. You should totally drop that and use jQuery UI

You can format it like this then

var str = $.datepicker.formatDate('yy-mm-dd', new Date("Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)");

I found Web Developer's Notes helpful in formatting dates


For things like this it's often good to do a little testing in the browser console.

var date = new Date("Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)");
console.log(date.getFullYear() + '-' + date.getMonth()+1 + '-' + date.getDate())

Ensure you add + 1 to the result of getMonth() because it is zero based.

A similar question was asked here:

Where can I find documentation on formatting a date in JavaScript?


jsFiddle Demo

Split the string based on the blank spaces. Take the parts and reconstruct it.

function convertDate(d){
 var parts = d.split(" ");
 var months = {Jan: "01",Feb: "02",Mar: "03",Apr: "04",May: "05",Jun: "06",Jul: "07",Aug: "08",Sep: "09",Oct: "10",Nov: "11",Dec: "12"};
 return parts[3]+"-"+months[parts[1]]+"-"+parts[2];
}

var d = "Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)";
alert(convertDate(d));