时间格式化-中文

168 阅读1分钟
function getTime(time = new Date()) {
    const timeStr = ["零", "一","二","三","四","五","六", "七", "八", "九", "十"];
    const newTime = new Date(time);
  
    // 补零操作,数字需要此操作,中文不需要 
    function zero(time) { 
        return time > 9 ? time : '0' + time; 
    }
    
    // 根据不同情况把月日时分秒转化为中文,① 0-10 ② 11-19 ③ 20,30... ④ 21-29,31-39...
    function getTimeStr(time) {
        // 先拆分 十位 和 个位 数
        const a = parseInt(time / 10);
        const b = time % 10;
        if (time <= 10) {
            return timeStr[time];
        } else if (time < 20) {
            return '十' + timeStr[b];
        } else if (time % 10 === 0) {
            return timeStr[a] + '十';
        } else {
            return timeStr[a] + '十' + timeStr[b];
        }
    }
    
    // 把年份转化为中文
    function yearStr(year) {
        const a = parseInt(year / 1000);
        const b = parseInt(year % 1000 / 100);
        const c = parseInt(year % 100 / 10);
        const d = year % 10;
        return timeStr[a] + timeStr[b] + timeStr[c] + timeStr[d];
  }

    const year = newTime.getFullYear();
    const month = newTime.getMonth() + 1;
    const day = newTime.getDate();
    const hours = newTime.getHours();
    const minutes = newTime.getMinutes();
    const seconds = newTime.getSeconds();
    const date = newTime.getDay();
  
  // 如果需要分上午和下午,把小时做一下处理输出
    return `${yearStr(year)}${getTimeStr(month)}${getTimeStr(day)}日星期${getTimeStr(date)}${hours > 12 ? '下午' : '上午'}${getTimeStr(hours > 12 ? hours - 12 : hours)}${getTimeStr(minutes)}${getTimeStr(seconds)}秒`;
}

const nowTime = getTime(1636721972000);
console.log(nowTime);