封装一个函数,将传入的时间戳转换为某些日期格式,如 time(15665568763,格式1) -」 YYYY-MM-DD hh:mm:ss

封装一个函数,将传入的时间戳转换为某些日期格式:

       function tranFormat(num, mat) {
            var date = new Date(num);
            var year = date.getFullYear();
            var month = date.getMonth() + 1;
            var day = date.getDate();
            var hour = date.getHours();
            var minute = date.getMinutes();
            var second = date.getSeconds();


            //indexOf :检索遇到的第一字符,返回下标,如果没有,返回-1
            //replace :replace(a,b) 使用b字符替换a字符,返回替换的字符串
            //三元运算符 条件 ? 执行1 : 执行2 ;   条件为true时执行1  条件为false执行2
            mat = mat.indexOf('Y') > -1 ? mat.replace('YYYY', year ) : mat;
            mat = mat.indexOf('M') > -1 ? mat.replace('MM', month < 10 ? '0' + month : month) : mat;
            mat = mat.indexOf('D') > -1 ? mat.replace('DD', day < 10 ? '0' + day : day) : mat;
            mat = mat.indexOf('h') > -1 ? mat.replace('hh', hour < 10 ? '0' + hour : hour) : mat;
            mat = mat.indexOf('m') > -1 ? mat.replace('mm', minute < 10 ? '0' + minute : minute) : mat;
            mat = mat.indexOf('s') > -1 ? mat.replace('ss', second < 10 ? '0' + second : second) : mat;
            return mat;

        }
        var str = 'YYYY - MM - DD hh: mm: ss';
        var str1 = 'MM / DD / YYYY hh: mm: ss';
        document.write(tranFormat(15665568763,str) + '
'); document.write(tranFormat(15665568763,str1));

你可能感兴趣的:(H5)