日付変換 dateFormat - カスタム形式 'yyyy-MM-dd HH:mm:ss'

  1. 日付形式は「-」から「/」です。

日付を new Date('2018-08-08') で変換するとブラウザーの互換性の問題が発生するため、new Date('2018/08/08') 形式に変換することをお勧めします。

function dateTypeChange(date){
    if(date){
            date=date.replace(/-/g,'/');
    }
    return date;
};
  1. 日付形式の変換方法1:

使用例: dateFormat(dateTypeChange('2018-08-08 18:09:20'),'yyyy-MM-dd HH:mm:ss');

使用例:dateFormat('2018/08/08 18:09:20','yyyy-MM-dd HH:mm:ss');

「yyyy-MM-dd hh:mm:ss」、自分で定義できます。例: 「yyy 年 MM 月 dd 日 hh 時 mm 分 ss 秒」。

/**
a:参数格式:new Date(2018/08/08 12:04:05)
b:日期格式'yyyy-MM-dd HH:mm:ss'
*/
function dateFormat(a,b) {
    if (typeof a === 'string')
        return a;
    var o = {
        y: a.getFullYear(),
        m: a.getMonth(),
        d: a.getDate(),
        h: a.getHours(),
        i: a.getMinutes(),
        s: a.getSeconds(),
        w: (a.getDay() || 7)
    };
    return (b || _date_sf).replace('yyyy', o.y).replace('MM', strPad(o.m + 1)).replace('dd', strPad(o.d)).replace('HH', strPad(o.h))
        .replace('mm', strPad(o.i)).replace('ss', strPad(o.s))
        .replace('M', o.m + 1).replace('d', o.d).replace('H', o.h).replace('m', o.i).replace('s', o.s);
};
  1. 日付形式の変換方法2:

使用例: new Date().format("yyyy-MM-dd hh:mm:ss");

「yyyy-MM-dd hh:mm:ss」、自分で定義できます。例: 「yyy 年 MM 月 dd 日 hh 時 mm 分 ss 秒」。

Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};

おすすめ

転載: blog.csdn.net/pinhmin/article/details/128661884