牛客题1

 

 自己初步:

    function getNum(num) {
            return num < 10 ? "0" + num : num;
        }

        function getH(hh) {
            if (hh > 12) {
                hh = hh - 12;
            }
            return hh;
        }

        function formatDate(ndata, format) {
            let data = ndata;
            let monthArry = ['', '', '', '', '', '', '']
            let yyyy = data.getFullYear();
            let yy = data.getFullYear() % 100;
            let MM = getNum(data.getMonth() + 1);
            let M = data.getMonth() + 1;
            let dd = getNum(data.getDay());
            let d = data.getDay();
            let HH = data.getHours();
            let H = data.getHours();
            let hh = getNum(getH(data.getHours()));
            let h = getH(data.getHours());
            let mm = getNum(data.getMinutes());
            let m = data.getMinutes();
            let ss = getNum(data.getSeconds());
            let s = data.getSeconds();
            let w = monthArry[data.getDate()]
            return format.replace(/yyyy/, yyyy).replace(/MM/, MM).replace(/dd/, dd).replace(/HH/, HH).replace(/H/, H)
                .replace(/h/, h).replace(/hh/, hh).replace(/mm/,
                    mm).replace(/ss/, ss).replace(/w/, w);

        }

优化

 function formatDate1(date, format) {
            var month = date.getMonth() + 1
            var _date = date.getDate();
            var hours = date.getHours();
            var mHours = hours > 12 ? hours - 12 : hours;
            var minutes = date.getMinutes();
            var seconds = date.getSeconds();
            var weeks = ['日', '一', '二', '三', '四', '五', '六'];
            return format.replace('yyyy', date.getFullYear())
                .replace('yy', date.getYear() % 100)
                .replace('MM', month < 10 ? '0' + month : month)
                .replace('M', date.getMonth() + 1)
                .replace('dd', _date < 10 ? '0' + _date : _date)
                .replace('d', _date)
                .replace('HH', hours < 10 ? '0' + hours : hours)
                .replace('H', hours)
                .replace('hh', mHours < 10 ? '0' + mHours : mHours)
                .replace('H', mHours)
                .replace('mm', minutes < 10 ? '0' + minutes : minutes)
                .replace('m', date.getMinutes())
                .replace('ss', seconds < 10 ? '0' + seconds : seconds)
                .replace('s', date.getSeconds())
                .replace('w', weeks[date.getDay()])
        }

思路:根据字符串的replace方法。

replace() 方法用于在字符串中用一些字符替换另一些字符,或替换一个与正则表达式匹配的子串。

 

posted @ 2021-04-15 16:37  胡炖鱼  阅读(59)  评论(0编辑  收藏  举报