How to convert this complex date format to this in javascript

How to convert this format "Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)" only in 2014-01-31 to Javascript ?? I know it should be easy, but I didn’t get it from Google

+6
source share
6 answers
 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 a jQuery UI .

+9
source

jsFiddle Demo

Separate the string based on spaces. Take the parts and repair them.

 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)); 
+5
source

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 that you are trying to format the date. You should completely abandon this and use jQuery UI

You can format it so that

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

I found Notes for web developers useful in formatting dates

+3
source

For such things, it is often useful 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()) 

Make sure you add + 1 to the getMonth () result, because it is based on a zero value.

A similar question was asked here:

Where can I find date formatting documentation in JavaScript?

+1
source

You can also use the Moment.js library, do not forget to give it a search.

A few examples: moment().format('MMMM Do YYYY, h:mm:ss a');

 moment().format('dddd'); 
0
source
 A trifling refinement: var date = new Date(value); var year = date.getFullYear(); var rawMonth = parseInt(date.getMonth()) + 1; var month = rawMonth < 10 ? '0' + rawMonth : rawmonth; var rawDay = parseInt(date.getDate()); var day = rawDay < 10 ? '0' + rawDay : rawDay; console.log(year + '-' + month + '-' + day); 
0
source

All Articles