这个日期时间格式该怎么处理

我获取一个出生日期,如:19940101 1994-01-01 1994.01.01 1994/01/01 1994-1-1 1994.1.1 1994/1/1,就可能是其中一种日期,我该怎么样才能将其转换为yyyy-mm-dd的格式?

阅读 2.8k
3 个回答
function formatTime(str) { 
    return str.replace(/\D/g,'')
        .replace(/(\d{4})(\d{1,2})(\d{1,2})/, (_,$1,$2,$3) => $1 + '-' + $2.padStart(2,'0') + '-' + $3.padStart(2,'0')) 
}

豆芽图片20200108145752.png

除了第一个,其他都应该适用

/**
*   @param {string}date 具体日期变量 
*   @param {string} dateType 需要返回类型
*   @return {string} dateText 返回为指定格式的日期字符串 
*/
function getFormatDate(date, dateType) { 
    let dateObj = new Date(date);
    let month = dateObj.getMonth() + 1; 
    let strDate = dateObj.getDate();
    let hours = dateObj.getHours(); 
    let minutes = dateObj.getMinutes(); 
    let seconds = dateObj.getSeconds(); 
    if (month >= 1 && month <= 9) { 
        month = "0" + month;
    } 
    if (strDate >= 0 && strDate <= 9) { 
        strDate = "0" + strDate;
    } 
    if (hours >= 0 && hours <= 9) { 
        hours = "0" + hours 
    } 
    if (minutes >= 0 && minutes <= 9) {
        minutes = "0" + minutes 
    } 
    if (seconds >= 0 && seconds <= 9) { 
        seconds = "0" + seconds 
    } 
    let dateText = dateObj.getFullYear() + '年' + (dateObj.getMonth() + 1) + '月' + dateObj.getDate() + '日'; 
    if (dateType == "yyyy-mm-dd") { 
        dateText = dateObj.getFullYear() + '-' + (dateObj.getMonth() + 1) + '-' + dateObj.getDate(); 
    }
    if (dateType == "yyyy.mm.dd") { 
        dateText = dateObj.getFullYear() + '.' + (dateObj.getMonth() + 1) + '.' + dateObj.getDate();
    } 
    if (dateType == "yyyy-mm-dd MM:mm:ss") { 
        dateText = dateObj.getFullYear() + '-' + month + '-' + strDate + ' ' + hours + ":" + minutes + ":" + seconds; 
    } 
    if (dateType == "mm-dd MM:mm:ss") { 
        dateText = month + '-' + strDate + ' ' + hours + ":" + minutes + ":" + seconds; 
    } 
    if (dateType == "yyyy年mm月dd日 MM:mm:ss") { 
        dateText = dateObj.getFullYear() + '年' + month + '月' + strDate + '日' + ' ' + hours + ":" + minutes + ":" + seconds;
    }
    return dateText;
}

;

推荐使用moment,上述所有时间格式皆可转化

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题