Reputation: 123
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
Upvotes: 9
Views: 77899
Reputation: 563
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 :)
Upvotes: 1
Reputation: 11
start_date="14 Feb 2020";
var new_startDate= new Date(start_date);
var date= moment(new_startDate).format('YYYY-MM-DD');
Answer: 2020-02-14
In here you have to use moment.js
Upvotes: 1
Reputation: 41
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);
Upvotes: 0
Reputation: 82337
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));
Upvotes: 9
Reputation: 133
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?
Upvotes: 4
Reputation: 7426
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
Upvotes: 8