How can I convert this format "Fri Jan 31 2014 00:00:00 GMT-0800 (Pacific Standard Time)"
to just 2014-01-31
in Javascript ?? I know it should be simple but I didnt get it from google
To convert a dd/mm/yyyy string to a date:Split the string on each forward slash to get the day, month and year. Pass the year, month minus 1 and the day to the Date() constructor. The Date() constructor creates and returns a new Date object.
The preferred Javascript date formats are: Dates Only — YYYY-MM-DD. Dates With Times — YYYY-MM-DDTHH:MM:SSZ.
The easiest way to convert is
new Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'long',
day: '2-digit'
}).format(new Date('Your Date'))
Just Replace 'Your Date' with your complicated date format :)
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.
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));
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With