Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 699
user3097566 Avatar asked Dec 13 '13 00:12

user3097566


People also ask

How convert dd MM yyyy string to date in JavaScript?

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.

What is this date format JavaScript?

The preferred Javascript date formats are: Dates Only — YYYY-MM-DD. Dates With Times — YYYY-MM-DDTHH:MM:SSZ.


4 Answers

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 :)

like image 149
RISHU GUPTA Avatar answered Nov 01 '22 04:11

RISHU GUPTA


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.

like image 34
Matt Avatar answered Nov 01 '22 02:11

Matt


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));
like image 45
Travis J Avatar answered Nov 01 '22 04:11

Travis J


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

like image 24
scrblnrd3 Avatar answered Nov 01 '22 04:11

scrblnrd3