首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計疑難解答

JavaScript 數字轉中文大寫/漢字數字:年份選擇器實戰示例

     編輯:程式設計疑難解答

需求場景

將數字年份(如 2015)轉為漢字顯示(二〇一五),用於日期選擇器的年份下拉選單,提升中文用戶體驗。

核心轉換函數

/**
 * 數字字符串轉漢字數字
 * @param {number|string} v - 數字或數字字符串
 * @returns {string} 漢字表示,如 "二〇一五"
 */
function toCNNumber(v) {
    const cn = '〇一二三四五六七八九'; // 注意:用 〇 而非 O
    return String(v).split('').map(ch => cn[parseInt(ch, 10)]).join('');
}

// 測試
console.log(toCNNumber(2015)); // "二〇一五"
console.log(toCNNumber('2024')); // "二〇二四"

關鍵點:使用 〇 (U+3007) 而非字母 O,語義正確且排版美觀。

完整年份選擇器生成代碼

<script>
function toCNNumber(v) {
    const cn = '〇一二三四五六七八九';
    return String(v).split('').map(ch => cn[parseInt(ch, 10)]).join('');
}

const now = new Date();
const curYear = now.getFullYear();
const RANGE = 20; // 前後 20 年

let cnOpts = '', numOpts = '';
for (let y = curYear - RANGE; y <= curYear + RANGE; y++) {
    cnOpts += `<option value="${y}">${toCNNumber(y)}</option>`;
    numOpts += `<option value="${y}">${y}</option>`;
}

// 月份、日期選項(純數字即可)
let monthOpts = '', dayOpts = '';
for (let m = 1; m <= 12; m++) monthOpts += `<option value="${m}">${m}</option>`;
for (let d = 1; d <= 31; d++) dayOpts += `<option value="${d}">${d}</option>`;
</script>

<!-- 漢字年份選擇器 -->
<select id="yearCN"><script>document.write(cnOpts)</script></select> 年
<select id="month"><script>document.write(monthOpts)</script></select> 月
<select id="day"><script>document.write(dayOpts)</script></select> 日

<!-- 純數字年份選擇器(對比) -->
<select id="yearNum"><script>document.write(numOpts)</script></select> 年

進階:農歷年份/生肖顯示

若需顯示「甲子年」「乙丑年」等干支紀年,需引入農歷庫(如 lunar-javascript):

import Lunar from 'lunar-javascript';
const lunar = Lunar.fromDate(new Date());
console.log(lunar.getYearInGanZhi()); // "甲辰年" (2024)
console.log(lunar.getYearShengXiao()); // "龍"

常見坑點與最佳實踐

問題解決
用字母 O 代替 〇嚴格使用 U+3007 圓圈字符,語義正確、字體渲染一致
document.write 阻塞渲染現代項目改用 select.innerHTML = cnOpts 或框架綁定
月份/日期未聯動校驗用 new Date(year, month, 0).getDate() 獲取當月天數動態更新
舊瀏覽器不支持 const/箭頭函數構建時用 Babel 轉譯,或寫 ES5 兼容寫法

擴展:通用數字轉中文庫

支援萬/億單位、小數、負數的完整實現可參考 number-to-chinese npm 包或自行實現分段轉換邏輯。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved