js标准时间格式化

Mon Jun 25 2018 15:19:07 GMT+0800

这个时间怎么格式化成年月日 2018-06-25

有没有直接的js方法不是插件那种

阅读 20.4k
4 个回答
//格式化日期:yyyy-MM-dd
function formatDate(date) {
    var myyear = date.getFullYear();
    var mymonth = date.getMonth() + 1;
    var myweekday = date.getDate();
 
    if (mymonth < 10) {
        mymonth = "0" + mymonth;
    }
    if (myweekday < 10) {
        myweekday = "0" + myweekday;
    }
    return (myyear + "-" + mymonth + "-" + myweekday);
}

var date = new Date();
//date
//Mon Jun 25 2018 15:32:38 GMT+0800 (中国标准时间)
formatDate(date);
//"2018-06-25"

更多 请看js获取日期及日期相关js方法 积累总结

var date = new Date('Mon Jun 25 2018 15:19:07 GMT+0800');
console.log(date.toLocaleDateString().replace(/\//g,'-'));
function formatDate(dateArg) {
    const date = new Date(dateArg);
    const year = date.getFullYear();
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const formatMonth = month < 10 ? `0${month}` : month;
    const formatDay = day < 10 ? `0${day}` : day;

    return `${year}-${formatMonth}-${formatDay}`
}
var date = new Date('2018/6/25')
date.toLocaleDateString('cn',{year: 'numeric', month: '2-digit', day: '2-digit' }).replace(/\//g, '-')
推荐问题
宣传栏