This function takes a date object as a parameter and returns a string in MM/DD/YYYY
format :
function format(date) {
return [
('0' + (date.getMonth() + 1)).slice(-2),
('0' + date.getDate()).slice(-2),
date.getFullYear()
].join('/')
}
Usage example (gives today's date in MM/DD/YYYY
format) :
format(new Date) // "01/03/2014"
You can easily change the resulting format with a few modifications :
function format(date) {
return [
date.getDate(),
date.getMonth() + 1,
('' + date.getFullYear()).slice(-2)
].join('-')
}
Usage example (gives today's date in D-M-YY
format) :
format(new Date) // "3-1-14"
Playing around
I've tuned the function a bit, this might be interesting for very basic needs :)
function format(date, format) {
var i = 0, bit;
if (!format) format = 'MM/DD/YYYY'; // default
format = format.split(/([^DMY]+)/i);
while (bit = format[i]) {
switch (bit.charAt(0).toUpperCase()) {
case 'D': format[i] = date.getDate(); break;
case 'M': format[i] = date.getMonth() + 1; break;
case 'Y': format[i] = date.getFullYear(); break;
}
if (bit.length === 2) {
format[i] = ('0' + format[i]).slice(-2);
}
i += 2;
}
return format.join('');
}
Usage examples :
format(new Date) // "01/03/2014" (default)
format(new Date, 'd/m/y') // "3/1/2014"
format(new Date, 'D/M/Y') // "3/1/2014"
format(new Date, 'DD-MM-YY') // "03-01-14"
format(new Date, 'M/YY') // "1/14"