日期转换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