javascript 日付から四半期を取得する
- 作成日 2022.09.08
- 更新日 2022.09.13
- javascript
- javascript

javascriptで、日付から四半期を取得するサンプルコードを記述してます。
環境
- OS windows11 pro 64bit
- Apache 2.4.43
- ブラウザ chrome 105.0.5195.102
四半期を取得
日付から四半期を取得するには、月を「3」で割って「+1」することで可能です。
function getQ(date = new Date()) {
return Math.floor(date.getMonth() / 3 + 1);
}
console.log(getQ(new Date('2022-01-07'))); // 1
console.log(getQ(new Date('2022-02-07'))); // 1
console.log(getQ(new Date('2022-03-07'))); // 1
console.log(getQ(new Date('2022-04-07'))); // 2
console.log(getQ(new Date('2022-05-07'))); // 2
console.log(getQ(new Date('2022-06-07'))); // 2
console.log(getQ(new Date('2022-07-07'))); // 3
console.log(getQ(new Date('2022-08-07'))); // 3
console.log(getQ(new Date('2022-09-07'))); // 3
console.log(getQ(new Date('2022-10-07'))); // 4
console.log(getQ(new Date('2022-11-07'))); // 4
console.log(getQ(new Date('2022-12-07'))); // 4
関数をそのまま実行すると、現在日付の四半期が取得されます。
function getQ(date = new Date()) {
return Math.floor(date.getMonth() / 3 + 1);
}
console.log(new Date()); // Wed Sep 07 2022 11:35:18 GMT+0900 (日本標準時)
console.log(getQ()); // 3
サンプルコード
以下は、日付を選択して「判定」ボタンをクリックする四半期を取得して表示するサンプルコードとなります。
※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 date = new Date( document.getElementById('day').value );
// 結果を表示
document.getElementsByClassName("badge")[0].textContent = Math.floor( date.getMonth() / 3 + 1 );
}
</script>
</body>
</html>
結果が表示されていることが確認できます。

-
前の記事
Redis 一度に複数keyの値を取得する 2022.09.08
-
次の記事
javascript tableのtr要素を作成する 2022.09.08
コメントを書く