OneStig OneStig - 7 days ago 7
Javascript Question

How do i get a date in YYYY-MM-DD format?

Normally if I wanted to get the date I could just do

var date = Date();
except the problem with that is it gives me a lot of stuff that I don't want like "GMT-0700" or something like that. How could I get a variable to equal "YYYY-MM-DD"?

Answer

The below code is a way of doing it. If you have a date, pass it to the convertDate() function and it will return a string in the YYYY-MM-DD format:

var todaysDate = new Date();

function convertDate(date) {
  var yyyy = date.getFullYear().toString();
  var mm = (date.getMonth()+1).toString();
  var dd  = date.getDate().toString();

  var mmChars = mm.split('');
  var ddChars = dd.split('');

  return yyyy + '-' + (mmChars[1]?mm:"0"+mmChars[0]) + '-' + (ddChars[1]?dd:"0"+ddChars[0]);
}

console.log(convertDate(todaysDate)); // Returns: 2015-08-25