1507. 转变日期格式

1507. 转变日期格式

1507. 转变日期格式_第1张图片


JS代码:

/**
 * @param {string} date
 * @return {string}
 */
var reformatDate = function(date) {
    let arr = date.split(' ');
    let day = arr[0].replace(/th|nd|rd|st/ig, '')    
    let monthList = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    let month = (monthList.indexOf(arr[1]) + 1).toString();  // 转换成String,方便后续判断长度

    return arr[2] + "-" + (month.length == 1 ? ("0" + month) : month) + "-" + (day.length == 1 ? ("0" + day) : day);
};
var reformatDate = function(date) {
    let dateList = date.split(' ');

    const monthList = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    let month = monthList.indexOf(dateList[1]) + 1;
    month = month < 10 ? '0' + month : month;  // 转换成字符串

    // let day = dateList[0].substring(0, dateList[0].length - 2);
    let day = parseInt(dateList[0]);
    day = day < 10 ? '0' + day : day;  // 转换成字符串

    return `${dateList[2]}-${month}-${day}`;
}

你可能感兴趣的:(LeetCode刷题,算法)