日期格式化

const defaultFormat='yyyy/MM/DD HH:mm:ss MS d';
    const REGS={
        year:/y{2,4}/,
        month:/M{1,2}(?!S)/,
        date:/D{1,2}/,
        hour:/H{1,2}/,
        minute:/m{1,2}/,
        second:/s{1,2}/,
        day:/d/,
        mill:/MS/,
        split:/[^a-z\d]/ig
    };

    function formatDig(num){
        return num>9?''+num:'0'+num;
    }

    function toWeek(index){
        return '周'+(['日','一','二','三','四','五','六'][index]);
    }
    function translateStrToDate(str,format=defaultFormat){
        format=format.split(REGS.split);
        str=str.split(REGS.split);
        let date={
            year:1900,
            month:1,
            date:1,
            hour:0,
            minute:0,
            second:0,
            mill:0
        };
        let regkeys=Object.keys(REGS);
        format.forEach(function(item,index){
            regkeys.forEach(function(reg){
                if(REGS[reg].test(item)){
                    date.hasOwnProperty(reg) && (date[reg]=str[index]);
                }
            })
        });
        date=Object.keys(date).map(function(item,index){
            if(index == 1){
                return parseInt(date[item],10)-1;
            }
            return parseInt(date[item],10);
        });
        date.unshift(Date);
        return new (Date.bind.apply(Date,date))();
    }
    console.log(translateStrToDate('2018/01/23 12:23:11 200'));
    console.log(translateStrToDate('2018 01 23','yyyy mm DD'));

    function translateDateToStr(date=new Date(),format=defaultFormat) {
        const obj={
            year:date.getFullYear(),
            month:date.getMonth(),
            date:date.getDate(),
            hour:date.getHours(),
            minute:date.getMinutes(),
            second:date.getSeconds(),
            mill:date.getMilliseconds(),
            day:toWeek(date.getDay())
        };
        Object.keys(REGS).forEach(function(item){
            format=format.replace(REGS[item],function(match){
                switch(item){
                    case 'year':
                    case 'mill':
                        return obj[item];
                    case 'split':
                        return match;
                    case 'month':
                        ++obj[item];
                    default:
                        return match.length == 2?formatDig(obj[item]):obj[item];
                }
            });
        });
        return format;
    }
    console.log(translateDateToStr());
    console.log(translateDateToStr(new Date(),'yyyy-MM-DD H:m:s d MS'));

你可能感兴趣的:(js)