JavaScript修改日期格式

<script>

//封装时间格式

function format(time, format) {

var t = new Date(time);

var tf = function (i) {

return (i < 10 ? '0' : '') + i

};

return format.replace(/yyyy|MM|dd|HH|mm|ss/g, function (a) {

switch (a) {

case 'yyyy':

return tf(t.getFullYear());

break;

case 'MM':

return tf(t.getMonth() + 1);

break;

case 'mm':

return tf(t.getMinutes());

break;

case 'dd':

return tf(t.getDate());

break;

case 'HH':

return tf(t.getHours());

break;

case 'ss':

return tf(t.getSeconds());

break;

}

})

}

</script>

//引用

var getDate1=new Date();

console.log(getDate1); //输出Mon Oct 30 2017 14:33:20 GMT+0800 (中国标准时间)

var result1=format(getDate1,'yyyy-MM-dd');

console.log(result1); //输出2017-10-30

var getDate2=new Date().toLocaleDateString();

console.log(getDate2); //输出2017/10/30

var result2=format(getDate2,'yyyy-MM-dd');

console.log(result2); //输出2017-10-30