Formatting a Javascript Date for MySQL

I don’t like to code in JavaScript, but that’s the Ajax-y wave of the future. So I write it when I have to. This week I needed to format a Javascript date as a MySQL-style date like 2007-12-08.

JavaScript apparently doesn’t have a nice date formatting function or even a generalized sprintf. Another Javascript quirk is that the Date.getMonth() function returns 0-11, while the getDate() function returns 1-31. I’m not sure what the designer was thinking on that one.

I came up with this function…feel free to use it in your code with or without credit:

function formatDate(date1) {
  return date1.getFullYear() + ’-’ +
    (date1.getMonth() < 9 ? ‘0’ : “) + (date1.getMonth()+1) + ’-’ +
    (date1.getDate() < 10 ? '0’ : ”) + date1.getDate();
}