Skip to content

js time

遇见王斌 edited this page Jun 16, 2020 · 1 revision

Date 格式转字符串

需求

var newDate = new Date();

返回的 Date 格式:

Wed Dec 13 2017 16:00:00 GMT+0800 (中国标准时间)

而且是 object 类型的

所需求的格式为

2017-12-13 16:00:00

实现

var formatDate = function (date) {
    var y = date.getFullYear();
    var m = date.getMonth() + 1;
    m = m < 10 ? ('0' + m) : m;
    var d = date.getDate();
    d = d < 10 ? ('0' + d) : d;
    var h = date.getHours();
    var minute = date.getMinutes();
    minute = minute < 10 ? ('0' + minute) : minute;
    var second= date.getSeconds();
    second = minute < 10 ? ('0' + second) : second;
    return y + '-' + m + '-' + d+' '+h+':'+minute+':'+ second;
};

formatDate(Date())

Clone this wiki locally