javascript 年から下2桁のみを取得する

javascript 年から下2桁のみを取得する

javascriptで、年から下2桁のみを取得するサンプルコードを記述してます。

環境

  • OS windows11 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 105.0.5195.102

年から下2桁のみを取得

年から下2桁のみを取得するには、文字列に直して年単位で取得して「slice」に「-2」を指定することで可能です。

const year2 = new Date().getFullYear().toString().slice(-2);

console.log( year2 ); // 22
console.log( typeof year2 ); // string

数値型に変換する場合は、「Number」を使用します。

console.log( Number(year2) ); // 22
console.log( typeof Number(year2) ); // number

年度を指定しても同じです。

const year2 = new Date('2023-01-01').getFullYear().toString().slice(-2);

console.log( year2 ); // 23
console.log( typeof year2 ); // string

console.log( Number(year2) ); // 23
console.log( typeof Number(year2) ); // number

substring

「substring」を使用しても、同様のことが可能です。

const str = new Date('2023-01-01').getFullYear().toString()

const year2 = str.substring(str.length - 2);

console.log( year2 ); // 23
console.log( typeof year2 ); // string

console.log( Number(year2) ); // 23
console.log( typeof Number(year2) ); // number

両方とも、3桁の西暦の場合も下2桁を取得します。

const year2 = new Date('987-01-01').getFullYear().toString().slice(-2);

console.log( year2 ); // 87
console.log( typeof year2 ); // string

console.log( Number(year2) ); // 87
console.log( typeof Number(year2) ); // number


const str = new Date('987-01-01').getFullYear().toString()

const year2_2 = str.substring(str.length - 2);

console.log( year2_2 ); // 7
console.log( typeof year2_2 ); // string

console.log( Number(year2_2) ); // 7
console.log( typeof Number(year2_2) ); // number

サンプルコード

以下は、日付を選択して「取得」ボタンをクリックする下2桁を取得して表示するサンプルコードとなります。

※cssには「bootstrap material」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- MDB -->
  <link href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/4.2.0/mdb.min.css" rel="stylesheet" />
</head>

<body>

  <div class="container text-center w-50" style="margin-top:200px">

    <h2><span class="badge badge-success">結果</span></h2>

    <form>
      <div class="form-group">
        <label class="bmd-label-floating">日付</label>
        <input type="date" id="day">
      </div>
    </form>

    <button type="button" onclick="hoge()" class="btn btn-success mt-1">
      取得
    </button>

  </div>

  <script>

    function hoge() {

      // フォームの入力を取得
      let yaer2 = new Date( document.getElementById('day').value ).getFullYear().toString().substring(2);

      // 結果を表示
      document.getElementsByClassName("badge")[0].textContent = yaer2;

    }

  </script>

</body>

</html>

結果が表示されていることが確認できます。