web

Javascript/Typescript 數字年月轉國字年月

Posted by Peter on February 16, 2023

剛好有個機會需要在網頁上用到數字的月份跟年份轉成民國的月份跟年份,但都有點太多功能,尤其是會把十位跟百位加進去,又或是整個年月日都轉起來

因應這些,我簡單搞了一個大概轉到999都沒什麼問題的專門給民國年跟月的轉換,就貼在這裡。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/**
 * Convert arabic digits to Zh digits, specificly used on year and months
 * @param {number | string} digit arabic string or number to convert
 * @example
 * toZhDigit(110)
 * => "一一〇"
 */

function toZhDigit(digit: number | string): string {
  // setup ZH number array
  const zhMap = ["", "", "", "", "", "", "", "", "", ""];

  // check the type and modify it to string
  digit = typeof digit === "string" ? digit : digit.toString();

  // cut the number into small arrays
  const digitArray = digit.split("");

  // map the digit with zhArray
  const zhArray = <string[]>[];
  digitArray.forEach((digit) => {
    // change the second digit to "十" if there're only two digit
    if (digitArray.length === 2 && zhArray.length === 0 && digit === "1") {
      zhArray.push("");
      return;
    }
    // return the array if the number is "10"
    if (digitArray.length === 2 && zhArray[0] === "" && digit === "0"){
      return;
    }

    const numDigit = parseInt(digit);
    zhArray.push(zhMap[numDigit]);
  });

  // convert the array back to string again
  const result = zhArray.join("");
  return result;
}

由於這個是用typescript寫的,如果不會typescript的同學請用tsc toZhDigit.ts 就能轉成javascript了。