技术类--JS日期格式转换

日期格式转换

规则

VALUE

  • value值可以为毫秒的时间戳,例如:16481008820000
  • value可以为日期组合(可以为年,年月,年月日),例如:19781001
  • value可以为日期形式,例如:2000-1-1 或 2000/1/1
  • value可以为日期加时间,例如:2000-1-1 10:10:10
  • value值采用递进式,即年是必须的,如果有日的话,就必须有月。例如:2002、2002-10、2002-10-1
  • value值对于01和1是一致的
  • value可以为长日期、完整日期、短日期、ISO 日期,例如:19 Feb 2019、Monday February 25 2015
  • value的默认值为空
    FORMAT
  • format以yyyy、mm、dd、hh、mm、ss进行日期格式截取,且yyyy、mm、dd、hh、mm、ss都不限制大小写
  • format可以有时分秒
  • format值采用递进式,即年是必须的,如果有日的话,就必须有月。例如:yyyy/mm/dd hh:mm:ss、yyyy/mm/dd hh:mm、yyyy/mm/dd hh、yyyy/mm/dd、yyyy/mm、yyyy
  • format默认值为yyyy/MM/dd

HTML(用于测试JS)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./formatDate.js"></script>
    <script>
        var successList= [
            {value:'16481008820000',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'1648100882000',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'164810088200',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'16481008000',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'1648100000',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'164810000',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'19781001',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'197801',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'1640001',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'19781',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'1978',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'100',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'10',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'1',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'16481008820000',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'164810088200000',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'1648100882000000',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'3253679999900000',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'8640000000000000',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'8640000000000001',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'16481008820000000',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'1648100882000',format:'yyyy'},
            {value:'1648100882000',format:'yyyy/mm'},
            {value:'1648100882000',format:'yyyy/mm/dd'},
            {value:'1648100882000',format:'yyyy/mm/dd hh'},
            {value:'1648100882000',format:'yyyy/mm/dd hh:mm'},
            {value:'1648100882000',format:'yyyy年mm月dd hh/mm/ss'},
            {value:'1648100882000',format:'yyyy年mm月dd hh小时mm分钟ss秒'},
            {value:'1648100882000',format:'yyyymmdd hhmmss'},
            {value:'1648100882000',format:'yyyymm月dd hh/mm/ss'},
            {value:'1648100882000',format:'yyyy年mmdd hh/mm/ss'},
            {value:'1648100882000',format:'yyyy年mm月dd hhmm/ss'},
            {value:'1648100882000',format:'yyyy年mm月dd hh/mmss'},
            {value:'1648100882000',format:'yyyy年mm月dd hhmmss'},
            {value:'1648100882000',format:'yyyy年mmdd hhmmss'},
            {value:'1648100882000',format:'yyyymmdd hhmmss'},
            {value:'1648100882000',format:'adsfyyyyasdfmmadfdd asdfhhadfmmadsfss'},
            {value:'1648100882000',format:'yyyy/mm/dd hh:mm:s'},
            {value:'1648100882000',format:'yyyy-mm-dd hh:mm:ss'},
            {value:'1648100882000',format:'yyyy-mm'},
            {value:'1648100882000',format:'yyyy/mm/dd hh-mm-ss'},
            {value:'1648100882000',format:'yyyy/mm/dd hh-mm'}, 
            {value:'1648100882000',format:'yyyy/asd/ss hh:mm:ss'},
            {value:'1648100882000',format:'yyyy/mm/dd aas:mm:ss'},
            {value:'1648100882000',format:'yyyy/mm/dd hh:sd:ss'},
            {value:'1648100882000',format:'yyyy/mm/dd hh:mm:aa'},
            {value:'1648100882000',format:'yyy/mm/dd hh:mm:ss'},
            {value:'1648100882000',format:'yy/mm/dd hh:mm:ss'},
            {value:'1648100882000',format:'yyyy/m/dd hh:mm:ss'},
            {value:'1648100882000',format:'yyyy/mm/d hh:mm:ss'},
            {value:'1648100882000',format:'yyyy/mm/dd h:mm:ss'},
            {value:'1648100882000',format:'yyyy/mm/dd hh:m:ss'},
            {value:'1648100882000',format:'yyyy/mm/dd hh:mm:s'},
            {value:'1648100882000',format:'yyyy-mm-dd hh:mm:ss'},
            {value:'1648100882000',format:'yyyy-mm'},
            {value:'1648100882000',format:'yyyy/mm/dd hh-mm-ss'},
            {value:'1648100882000',format:'yyyy/mm/dd hh-mm'},
            {value:'1648100882000',format:'yyyy/mm/dd mm-ss'},                   
        ]
        var timte= [
            {value:'2000-1-11:1:1',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000-13-1 1:1:1',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000-1-32 1:1:1',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000-1-1 25:1:1',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000-1-1 1:61:1',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000-1-1 1:1:61',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000-1-1 1-1-1',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000-10-10 10:10:10',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000-1-1 1:1:1',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000-1-1',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000-1-1 ',format:'yyyy/mm/dd hh:mm:ss'},            
            {value:'2000/1/1',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'200011',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'Feb 19 2018',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'19 Feb 2019',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'Monday February 25 2015',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000-01',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'2000-1',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh:mm:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh:mm'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy年mm月dd hh/mm/ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy年mm月dd hh小时mm分钟ss秒'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyymmdd hhmmss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyymm月dd hh/mm/ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy年mmdd hh/mm/ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy年mm月dd hhmm/ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy年mm月dd hh/mmss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy年mm月dd hhmmss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy年mmdd hhmmss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyymmdd hhmmss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'adsfyyyyasdfmmadfdd asdfhhadfmmadsfss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh:mm:s'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy-mm-dd hh:mm:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy-mm'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh-mm-ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh-mm'}, 
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/asd/ss hh:mm:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd aas:mm:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh:sd:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh:mm:aa'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyy/mm/dd hh:mm:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yy/mm/dd hh:mm:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/m/dd hh:mm:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/d hh:mm:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd h:mm:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh:m:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh:mm:s'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy-mm-dd hh:mm:ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy-mm'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh-mm-ss'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd hh-mm'},
            {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy/mm/dd mm-ss'},                   
        ]
        var s = [
        {value:'Mon Feb 19 2018 06:00:00 GMT+0800 (中国标准时间)',format:'yyyy-mm-dd hh:mm:ss'},
        ]
        console.time("elapsedTime")
        for(let i = 0;i < s.length;i++ ){
            var result = formatDate(s[i]['value'],s[i]['format']);
            console.log(result)
        }
        console.timeEnd("elapsedTime")
    </script>
</head>
<body>
    
</body>
</html>

Javascript

function formatDate(value, format) {
    var tempVal = value + '';
    tempVal = tempVal.trim();
    format = format.trim();
    // 判断value是否存在
    var isExists_value_return = isExists_value(tempVal);
    //  判断format是否存在
    var isExists_format_return = isExists_format(format);

    var valType = isValid_value(isExists_value_return);

    var formatList = parseFormat(isExists_format_return);

    var timestamp = '';
    if(valType == "timestamp"){
        timestamp = isExists_value_return;
    }else if(valType == "date"){
        if(formatList['type'] == "time"){
            isExists_value_return = isExists_value_return + " " + "00:00:00"
        }
        var newDateTemp = new Date(isExists_value_return);
        timestamp = Date.parse(newDateTemp);
    }else if(valType == "dateTime"){
        var newDateTemp = new Date(isExists_value_return);
        timestamp = Date.parse(newDateTemp);
    }else if(valType == "dateNum"){        
        var newVals = isExists_value_return;
        if(isExists_value_return.length > 6 && isExists_value_return.length <= 8){
            var days = parseInt(new Date(parseInt(isExists_value_return.slice(0,4)),parseInt(isExists_value_return.slice(4,6)),0).getDate());
            if((parseInt(isExists_value_return.slice(0,4)) >= 1970) && (parseInt(isExists_value_return.slice(4,6)) > 0 && parseInt(isExists_value_return.slice(4,6)) < 13) && (isExists_value_return.slice(6,isExists_value_return.length) > 0 && isExists_value_return.slice(6,isExists_value_return.length) <= days)){
                newVals = isExists_value_return.slice(0,4) + '-' + isExists_value_return.slice(4,6) + '-' +isExists_value_return.slice(6,isExists_value_return.length); 
            }else{
                console.warn("invalid value!");
                return "";
            }
            
        }else if(isExists_value_return.length > 4 && isExists_value_return.length <= 6){
            if((parseInt(isExists_value_return.slice(0,4)) >= 1970) && (parseInt(isExists_value_return.slice(4,6)) > 0 && parseInt(isExists_value_return.slice(4,6)) < 13)){
                newVals = isExists_value_return.slice(0,4) + '-' + isExists_value_return.slice(4,isExists_value_return.length);
            }else{
                console.warn("invalid value!");
                return "";
            }
        }else{
            newVals = isExists_value_return; 
        }
        if(formatList['type'] == "time"){
            newVals = newVals + " " + "00:00:00";
        }        
        var newDateTemp = new Date(newVals);
        timestamp = Date.parse(newDateTemp);
    }else{
        console.warn("invalid value!");
        return "";
    }
    if(parseInt(timestamp) > 8640000000000000 || parseInt(timestamp) < -8640000000000000){
        console.warn("invalid value!");
        return "";
    }
    if(formatList['type'] == "noFormat"){
        console.warn("invalid format!");
        return "";
    }else if(formatList['type'] == "date"){
        return dateChange(timestamp,formatList);  
    }else if(formatList['type'] == "time"){
        var dateParts = dateChange(timestamp,formatList);
        var timeParts = timeChange(timestamp,formatList);
        return dateParts + " " + timeParts;
    }else{
        console.info(value);
    }
}

// 判断value是否存在
function isExists_value(value) {
    var newValue = value.trim();
    if (newValue == '' || newValue == null || newValue == undefined) {
        return '';
    }
    return newValue;
}
// 判断value是否合法
function isValid_value(value) {
    var type = "date";
    var numReg = /(^[0-9]\d*$)/;
    if (numReg.test(value)) {
        if (value.length >= 9) {
            type = "timestamp";
        } else {
            type = "dateNum";
        }
    } else {
        if (isNaN(value) && !isNaN(Date.parse(value))) {
            if (value.indexOf(" ") != -1 || value.toLowerCase().indexOf("t") != -1) {
                type = "dateTime";
            } else {
                type = "date";
            }
        } else {
            type = "noDate";
        }
    }
    return type;
}
//  判断format是否存在
function isExists_format(format) {
    var newformat = format.trim();
    if (newformat == '' || newformat == null || newformat == undefined) {
        newformat = "yyyy/MM/dd";
    }
    return newformat;
}
// 解析format
function parseFormat(format) {
    var day = false;
    var month = false;
    var year = false;
    var hour = false;
    var minute = false;
    var second = false;
    var dateArr = ["","","",""];
    var timeArr = ["","","",""];
    var formatList = {};

    if (format.indexOf(" ") != -1) {
        var datePart = format.split(" ")[0].toLowerCase();
        var timePart = format.split(" ")[1].toLowerCase();
    } else {
        var datePart = format;
    }

    //判断日期的格式
    year = isIndexOf(datePart, "yyyy");
    var type = "date";

    if (year) {
        var dateArr = [];
        var tempY = datePart.split('yyyy');
        dateArr[0] = tempY[0];
        month = isIndexOf(datePart, "mm");
        if (month) {
            dateArr[1] = tempY[1].split("mm")[0];
            day = isIndexOf(datePart, "dd");
            if (day) {
                dateArr[2] = tempY[1].split("mm")[1].split("dd")[0];
                if (format.indexOf(" ") != -1) {
                    var type = "time";
                    
                    dateArr[3] = tempY[1].split("mm")[1].split("dd")[1].split(" ")[0];
                    hour = isIndexOf(timePart, "hh");
                    if (hour) {
                        var tempH = timePart.split('hh');
                        timeArr[0] = tempH[0];
                        minute = isIndexOf(timePart, "mm");
                        if(minute){
                            timeArr[1] = tempH[1].split("mm")[0];
                            second = isIndexOf(timePart, "ss");
                            if(second){
                                timeArr[2] = tempH[1].split("mm")[1].split("ss")[0];
                                timeArr[3] = tempH[1].split("mm")[1].split("ss")[1];
                            }else{
                                timeArr[2] = tempH[1].split("mm")[1];
                            }
                        }else{
                            timeArr[1] = tempH[1];
                        }
                    }
                } else {
                    dateArr[3] = tempY[1].split("mm")[1].split("dd")[1];
                }
            } else {
                dateArr[2] = tempY[1].split("mm")[1];
            }
        }else{
            dateArr[1] = tempY[1];
        }
    } else {
        type = "noFormat";
    }

    formatList['type'] = type;
    formatList['year'] = year;
    formatList['month'] = month;
    formatList['day'] = day;
    formatList['hour'] = hour;
    formatList['minute'] = minute;
    formatList['second'] = second;
    formatList['dateArr'] = dateArr;
    formatList['timeArr'] = timeArr;

    return formatList;
}

function isIndexOf(str, part) {
    if (str.indexOf(part) != -1) {
        return true;
    } else {
        return false;
    }
}
// 转换日期部分
function dateChange(timestamp, formatList) {
    var newDate = new Date(parseInt(timestamp));
    var Y = "";
    var M = "";
    var D = "";
    if (formatList['year']) {
        Y = newDate.getFullYear();
        Y = formatList['dateArr'][0] + Y;
    }
    if (formatList['month']) {
        M = (newDate.getMonth() + 1 < 10 ? '0' + (newDate.getMonth() + 1) : newDate.getMonth() + 1);
        M = formatList['dateArr'][1] + M;
    }
    if (formatList['day']) {
        D = newDate.getDate()  < 10 ? '0' + newDate.getDate() : newDate.getDate();
        D = formatList['dateArr'][2] + D;
        if(formatList['dateArr'][3]){
            D = D + formatList['dateArr'][3];
        }
    }

    return Y + M + D;
}
// 转换时间部分
function timeChange(timestamp, formatList) {
    var newTimeDate = new Date(parseInt(timestamp));
    var H = "";
    var m = "";
    var s = "";
    if (formatList['hour']) {
        H = newTimeDate.getHours() < 10 ? '0' + newTimeDate.getHours() : newTimeDate.getHours();
        H = formatList['timeArr'][0] + H;
    }
    if (formatList['minute']) {
        m = newTimeDate.getMinutes() < 10 ? '0' + newTimeDate.getMinutes() : newTimeDate.getMinutes();
        m = formatList['timeArr'][1] + m;
    }
    if (formatList['second']) {
        s = newTimeDate.getSeconds() < 10 ? '0' + newTimeDate.getSeconds() : newTimeDate.getSeconds();
        s = formatList['timeArr'][2] + s;
        if(formatList['timeArr'][3]){
            s = s + formatList['timeArr'][3];
        }        
    }

    return H + m + s;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值